How to Use GROUP by in SQL Server

Embed Size (px)

Citation preview

  • 7/28/2019 How to Use GROUP by in SQL Server

    1/38

    How to Use GROUP BY in SQL Server

    By Jeff Smithon 30 July 2007 | 7 Comments | Tags: Queries,SELECT

    Article Series Navigation:

    Summarizing data in a SELECT statement using a GROUP BYclause is a very

    common area of difficulty for beginning SQL programmers. In Part I of this two part

    series, we'll use a simple schema and a typical report request to cover the effect of

    JOINS on grouping and aggregate calculations, and how to use COUNT(Distinct) to

    overcome this. In Part II, we'll finish up our report while examining the problem

    with SUM(Distinct) and discussing how useful derived tables can be when grouping

    complicated data. (This article has been updated through SQL Server 2005. )

    Here's the schema we'll be using along with some sample data:

    create table Orders

    (

    OrderID int primary key,

    Customer varchar(10),

    OrderDate datetime,

    ShippingCost money

    )

    create table OrderDetails

    (

    DetailID int primary key,

    OrderID int references Orders(OrderID),

    Item varchar(10),

    Amount money

    )

    go

    insert into Orders

    select 1,'ABC', '2007-01-01', 40 union all

    select 2,'ABC', '2007-01-02', 30 union allselect 3,'ABC', '2007-01-03', 25 union all

    select 4,'DEF', '2007-01-02', 10

    insert into OrderDetails

    select 1, 1, 'Item A', 100 union all

    select 2, 1, 'Item B', 150 union all

    http://www.sqlteam.com/author/jeff-smithhttp://www.sqlteam.com/forums/topic.asp?TOPIC_ID=87059http://www.sqlteam.com/tag/sql-server-querieshttp://www.sqlteam.com/tag/sql-server-querieshttp://www.sqlteam.com/tag/selecthttp://www.sqlteam.com/author/jeff-smithhttp://www.sqlteam.com/forums/topic.asp?TOPIC_ID=87059http://www.sqlteam.com/tag/sql-server-querieshttp://www.sqlteam.com/tag/select
  • 7/28/2019 How to Use GROUP by in SQL Server

    2/38

    select 3, 2, 'Item C', 125 union all

    select 4, 2, 'Item B', 50 union all

    select 5, 2, 'Item H', 200 union all

    select 6, 3, 'Item X', 100 union all

    select 7, 4, 'Item Y', 50 union all

    select 8, 4, 'Item Z', 300

    Determining the Virtual Primary Key of a Result Set

    Let's examine our sample data by joining these tables together to return Orders

    along with the OrderDetails:

    select

    o.orderID, o.customer, o.orderdate, o.shippingCost, od.DetailID, od.Item, od.Amount

    from

    orders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

    orderID customer orderdate shippingCost DetailID Item Amount

    ----------- ---------- -------------- ------------- --------- ---------- ----------

    1 ABC 2007-01-01 40.0000 1 Item A 100.0000

    1 ABC 2007-01-01 40.0000 2 Item B 150.0000

    2 ABC 2007-01-02 30.0000 3 Item C 125.0000

    2 ABC 2007-01-02 30.0000 4 Item B 50.0000

    2 ABC 2007-01-02 30.0000 5 Item H 200.00003 ABC 2007-01-03 25.0000 6 Item X 100.0000

    4 DEF 2007-01-02 10.0000 7 Item Y 50.0000

    4 DEF 2007-01-02 10.0000 8 Item Z 300.0000

    (8 row(s) affected)

    Remember that Orders has a one-to-many or parent/child relationship with

    OrderDetails: thus, one order can have many details. When we join them

    together, the Order columns are repeated over and over for each OrderDetail. This

    is normal, standard SQL behavior and what happens when you join tables in a one-

    to-many relation. Our result contains one row per OrderDetail, and those

    OrderDetail rows are never repeated, since it is not being joined to any further

    tables that will produce duplicate rows.

    Thus, we could say that our result set has a virtual primary keyof DetailID; there

    will never be a duplicate OrderDetail row in the data. We can count and add up all

    OrderDetail columns and never worry about double counting values. However, we

  • 7/28/2019 How to Use GROUP by in SQL Server

    3/38

    can not do the same for the Orders table, since its rows are duplicated in the

    results. Remember this as we move forward.

    A Typical Summary Report Example

    Here is a good example using Orders and OrderDetails that demonstrates variousaggregate functions and typical things to look for:

    For each Customer, we want to return the total number of orders, the number of

    items ordered, the total order amount, and the total shipping cost.

    All of this information lives in the Orders and the OrderDetails tables, and we know

    how to join them together, we just need to summarize those results now. We don't

    want to return all 8 rows and see all of the details; we just want to return 2 rows:

    one per customer, with the corresponding summary calculations.

    Grouping and Summarizing Primary Rows

    Since we want to return 1 row for each Customer, we can simply add GROUP BY

    Customer to the end of the SELECT. We can return the Customer column since we

    are grouping on it, and we can add any other columns as long as they are

    summarized in an aggregate function. We can also use the COUNT(*) aggregate

    function to return the number of rows per group. Since each row in our data

    corresponds to an order item, grouping by Customer and selecting Customer

    and COUNT(*) will return the number of OrderDetails per Customer:

    select

    o.Customer, count(*) as ItemCount

    from

    Orders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

    group by

    o.Customer

    Customer ItemCount

    ---------- -----------

    ABC 6DEF 2

    (2 row(s) affected)

  • 7/28/2019 How to Use GROUP by in SQL Server

    4/38

    Next, lets add the total order amount per customer. Since our join resulted in one

    row per item detail (remember: when joining Orders to OrderDetails, the result set

    has a virtual primary keyof DetailID) we know that no rows in the OrderDetails

    table were duplicated in our results. Therefore, a simple SUM() of the Amount

    column from the OrderDetails table is all we need to return the total order amount

    per customer:

    select

    o.Customer, count(*) as ItemCount, sum(od.Amount) as OrderAmount

    from

    Orders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

    group by

    o.Customer

    Customer ItemCount OrderAmount

    ---------- ----------- ---------------------

    ABC 6 725.0000

    DEF 2 350.0000

    (2 row(s) affected)

    So far, so good! Only two more calculations to go: total orders per customer, and

    total shipping cost. Both of these values come from the Orders table.

    If you recall, our join resulted in one row per OrderDetail, and that meant that the

    Orders table had duplicate rows. We need to return two calculations from our

    Orders table -- total number of Orders, and total Shipping cost. We already know

    that COUNT(*)returns the number of OrderDetails, so that wont work for us.

    Perhaps COUNT(OrderID) will return the total number of orders? Let's try it:

    select

    o.Customer, count(*) as ItemCount, sum(od.Amount) as OrderAmount,

    count(o.OrderID) as OrderCount

    fromOrders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

    group by

    o.Customer

    Customer ItemCount OrderAmount OrderCount

  • 7/28/2019 How to Use GROUP by in SQL Server

    5/38

    ---------- ----------- --------------------- -----------

    ABC 6 725.0000 6

    DEF 2 350.0000 2

    (2 row(s) affected)

    Notice that the OrderCount column returned is the same as the ItemCount, and

    definitely not the number of orders per customer. That is because, by definition in

    SQL, COUNT(expression) just returns the total number of rows in which that

    expression is not null. Since OrderID is never null, it returns the total row count per

    Customer, and since each row corresponds with an OrderDetail item, we get the

    number of OrderDetail items per customer, not the number of Orders per

    customer.

    Using COUNT(Distinct)

    Luckily, there is a DISTINCTfeature that we can use in our COUNT() aggregate

    function that will help us here. Count(Distinct expression) means: " return the total

    number of distinct values for the specified expression." So, if we

    write COUNT(Distinct OrderID), it will return the distinct number of OrderID

    values per Customer. Since each OrderID value corresponds to an Order (it is the

    primary key of the Orders table), we can use this to calculate our Order count:

    select

    o.Customer, count(*) as ItemCount, sum(od.Amount) as OrderAmount,

    count(distinct o.OrderID) as OrderCount

    from

    Orders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

    group by

    o.Customer

    Customer ItemCount OrderAmount OrderCount

    ---------- ----------- --------------------- -----------

    ABC 6 725.0000 3DEF 2 350.0000 1

    (2 row(s) affected)

    Great! Looks good, makes sense, now we are getting somewhere.

  • 7/28/2019 How to Use GROUP by in SQL Server

    6/38

    Beware of SUMMING Duplicate Values

    Moving on, lets add an expression to calculate total shipping cost per customer.

    Well, we know we have a ShippingCost column in our data from the Orders table,

    so let's try just adding SUM(ShippingCost) to our SELECT:

    select

    o.Customer, count(*) as ItemCount, sum(od.Amount) as OrderAmount,

    count(distinct o.OrderID) as OrderCount, sum(o.ShippingCost) as TotalShipping

    from

    Orders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

    group by

    o.Customer

    Customer ItemCount OrderAmount OrderCount TotalShipping---------- ----------- --------------------- ----------- ---------------------

    ABC 6 725.0000 3 195.0000

    DEF 2 350.0000 1 20.0000

    (2 row(s) affected)

    Looks like we are good to go, right? Well -- not really, look at our TotalShipping

    column. Customer ABC has a total shipping of 195. Yet, in our Orders table, we see

    that the customer has 3 orders, with shipping values of 40,30 and 25.

    40+30+25=95, not 195! What is going on here? Well, like

    the COUNT(*) expression, remember that the SUM() is acting not upon our tables

    themselves, but the result of the JOIN that we expressed in our SELECT. The JOIN

    from Orders to OrderDetails meant that rows from the Orders table were

    duplicated, remember? So, if we SUM() a column in our Orders table when it is

    joined to the Details, we are summing up duplicate values and our result will be too

    high. You can verify this by reviewing the results returned by the join from Orders

    to OrderDetails and manually adding them up by hand.

    It is very important to understand this; when writing any JOINS, you need to

    identify which tables can and cannot have duplicate rows returned. The basic rule is

    very simple:

    If Table A has one-to-many relation with Table B, and Table A is JOINED to Table

    B, then Table A will have duplicate rows in the result. The final result will have a

    virtual primary key equal to that of Table B's.

    So, we know we can SUM() and COUNT() columns from Table B with no problem,

    but we cannot do that with columns from Table A because the duplicate values will

  • 7/28/2019 How to Use GROUP by in SQL Server

    7/38

    skew our results. How do we handle this situation? We'll cover that and a whole lot

    more in Part II, coming tomorrow.

    In How to Use GROUP BY, we worked on a simple report request and covered the

    basics ofGROUP BYand the issue of duplicate rows caused by JOINs. Today we'll

    finish up that report while examining SUM(Distinct), and see just how crucialderived tables are when summarizing data from multiple tables.

    The Problem with SUM(Distinct)

    We previously learned that we can use COUNT(Distinct) to count columns from the

    duplicated table, so what about SUM(Distinct)? It seems like that should do the

    trick, since we only want to sum distinct shipping cost values, not all the

    duplicates. Let's give it a try:

    select

    o.Customer, count(*) as ItemCount, sum(od.Amount) as OrderAmount,

    count(distinct o.OrderID) as OrderCount,

    sum(distinct o.ShippingCost) as TotalShipping

    from

    Orders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

    group by

    o.Customer

    Customer ItemCount OrderAmount OrderCount TotalShipping---------- ----------- --------------------- ----------- ---------------------

    ABC 6 725.0000 3 95.0000

    DEF 2 350.0000 1 10.0000

    (2 row(s) affected)

    And there it is! We seem to have solved our problem: looking back to our Orders

    table, we can see that the TotalShipping cost per Customer now looks correct.

    But wait ... It is actually wrong!

    This is where many people have problems. Yes, the data looks correct. And, for this

    small sample, it just randomly happens to be correct.

    But SUM(DISTINCT) works exactly the same as COUNT(DISTINCT): It simply gets

    all of the values eligible to be summed, eliminates all duplicate values, and then

    adds up the results. But it is eliminating duplicate values, not duplicate rows

    based on some primary key column! It doesn't care that shipping cost 40

    http://www.sqlteam.com/article/how-to-use-group-by-with-distinct-aggregates-and-derived-tableshttp://www.sqlteam.com/article/how-to-use-group-by-in-sql-serverhttp://www.sqlteam.com/article/how-to-use-group-by-with-distinct-aggregates-and-derived-tableshttp://www.sqlteam.com/article/how-to-use-group-by-in-sql-server
  • 7/28/2019 How to Use GROUP by in SQL Server

    8/38

    belonged to orderID #1 and that shipping cost 30 belonged to OrderID #2; it

    simply doesn't separate them that way.

    The expression SUM(Distinct ShippingCost) is basically evaluated like this:

    1.After Joining from Orders to OrderDetails, each group has the followingShipping cost values:

    Customer ABC: 40,40,30,30,30,25

    Customer DEF: 10

    2. Since DISTINCT was asked for, it eliminates duplicate values from those

    lists:

    Customer ABC: 40,40,30,30,30,25

    Customer DEF: 10

    3. And now it can evaluate the SUM() by adding up the remaining values:

    Customer ABC: 40+30+25 = 95

    Customer DEF: 10 = 10

    If you aren't getting the concept, you still might not see the problem. In fact, at

    this point, many people never do. They see thatSUM(x) returns huge numbers that

    cannot be right, so they tweak it and try SUM(DISTINCT x), and the values look

    much more reasonable, and they might even initially tie out perfectly, so off to

    production it goes. Yet, the SQL is incorrect; it is relying on the fact that currently

    no two orders for a customer have the same shipping cost.

    Let's demonstrate by adding another order:

    insert into Orders values (5, 'DEF', '2007-01-04', 10)

    insert into OrderDetails values (9, 5, 'Item J', 125)

    Running that simply adds another Order for Customer DEF, shipping cost of $10,

    with one OrderDetail item for $125. Now, let's execute that same SELECT again to

    see how this new Order affected our results:

    selecto.Customer, count(*) as ItemCount, sum(od.Amount) as OrderAmount,

    count(distinct o.OrderID) as OrderCount,

    sum(distinct o.ShippingCost) as TotalShipping

    from

    Orders o

    inner join

    OrderDetails od on o.OrderID = od.OrderID

  • 7/28/2019 How to Use GROUP by in SQL Server

    9/38

    group by

    Customer

    Customer ItemCount OrderAmount OrderCount TotalShipping

    ---------- ----------- --------------------- ----------- ---------------------

    ABC 6 725.0000 3 95.0000DEF 3 475.0000 2 10.0000

    (2 row(s) affected)

    The ItemCount, OrderAmount and OrderCount columns look great. But the

    TotalShipping cost for DEF still shows $10! What happened!?

    Can you figure it out? Remember how SUM(Distinct) works! It just takes distinct

    values passed to the function and eliminates duplicates. Both orders for DEF had ashipping cost of $10, and SUM(Distinct ShippingCost) doesn't care that the two

    $10 values are for different Orders, it just knows that the 10 is duplicated for the

    Customer, so it only uses the 10 once to calculate the SUM. Thus, it returns a value

    of 10 as the total shipping cost for those two orders, even though it should be

    10+10=20. Our result is now wrong. The long and short of it is this: Never

    use SUM(Distinct) ! It doesn't usually make logical sense in most situations; there

    may be a time and place for it, but it is definitely not here.

    Summarizing Derived Tables

    So, how do we fix this? Well, like many SQL problems, the answer is simple: Do itone step at a time, don't try to join all of the tables together and just

    add SUM() and GROUP BYand DISTINCTalmost randomly until things work; break

    it down logically step by step.

    So, before worrying about totals per Customer, let's step back and focus on

    returning totals per Order. If we can return totals per Order first, then we can

    simply summarize those Order totals by Customer and we'll have the results we

    need. Let's summarize the OrderDetails table to return 1 row per Order, with the

    ItemCount and the total Order Amount:

    selectorderID, count(*) as ItemCount, sum(Amount) as OrderAmount

    from

    orderDetails

    group by

    orderID

  • 7/28/2019 How to Use GROUP by in SQL Server

    10/38

    orderID ItemCount OrderAmount

    ----------- ----------- ---------------------

    1 2 250.0000

    2 3 375.0000

    3 1 100.0000

    4 2 350.00005 1 125.0000

    (5 row(s) affected)

    Nice and simple, easy to verify, things look good. Because we are grouping on

    OrderID, we can say that these results have a virtual primary key of OrderID --

    that is, there will never be duplicate rows for the same Order. In fact, here's

    another basic rule to always remember:

    The virtual primary key of a SELECT with a GROUP BY clause willalways be the

    expressions stated in the GROUP BY.

    We can now take that SQL statement and those results and encapsulate them in

    their own derived table. If we join from the Orders table to the previous SELECT as

    a derived table, we get:

    select

    o.orderID, o.Customer, o.ShippingCost, d.ItemCount, d.OrderAmount

    from

    orders oinner join

    (

    select

    orderID, count(*) as ItemCount, sum(Amount) as OrderAmount

    from

    orderDetails

    group by

    orderID

    ) d

    on o.orderID = d.orderID

    orderID Customer ShippingCost ItemCount OrderAmount

    ----------- ---------- --------------------- ----------- ---------------------

    1 ABC 40.0000 2 250.0000

    2 ABC 30.0000 3 375.0000

    3 ABC 25.0000 1 100.0000

    4 DEF 10.0000 2 350.0000

  • 7/28/2019 How to Use GROUP by in SQL Server

    11/38

    5 DEF 10.0000 1 125.0000

    (5 row(s) affected)

    Let's examine those results. There are no duplicate rows or values anywhere; there

    is exactly one row per Order. This is because our derived table has a virtual

    primary key of OrderID, so joining from Orders to our derived table will never

    produce duplicates. This is a very useful and simple technique to avoid duplicates

    when relating a parent table to a child table: summarize the child table by the

    parent's primary key first in a derived table, and then join it to the parent table.

    The parent tables rows will then never be duplicated and can be summarized

    accurately.

    Now we have our total ItemCount per order, as well as our total OrderAmount per

    order. And we can see that if we sum these results up, our ShippingCost columnwill be fine, since it is never duplicated. No need for distinct. In fact, we can even

    use a regularCOUNT(*) expression to get the total number of orders per customer!

    So, we can simply add "GROUP BY Customer" to the previous SQL, calculate what

    we need with aggregate functions, and remove any columns (like OrderID) that we

    will not be summarizing. You might also notice that at this point, the total

    ItemCount per Customer is no longer a COUNT(*) expression; it is a

    simple SUM() of the ItemCount value returned from our derived table.

    Here's the result:

    select

    o.Customer, count(*) as OrderCount,

    sum(o.ShippingCost) as ShippingTotal, sum(d.ItemCount) as ItemCount,

    sum(d.OrderAmount) as OrderAmount

    from

    orders o

    inner join

    (

    select

    orderID, count(*) as ItemCount, sum(Amount) as OrderAmount

    fromorderDetails

    group by

    orderID

    ) d

    on o.orderID = d.orderID

    group by

    o.customer

  • 7/28/2019 How to Use GROUP by in SQL Server

    12/38

    Customer OrderCount ShippingTotal ItemCount OrderAmount

    ---------- ----------- --------------------- ----------- ---------------------

    ABC 3 95.0000 6 725.0000

    DEF 2 20.0000 3 475.0000

    (2 row(s) affected)

    And there you have it! We examined our data, logically considered the implications

    of our JOINS, broke the problem down into smaller parts, and ended up with a

    fairly simple solution that we know will be quick, efficient and accurate.

    Adding More Tables a Summarized SELECT

    To finish things up, suppose our schema also has a table of Customers:

    Create table Customers

    (

    Customer varchar(10) primary key,

    CustomerName varchar(100) not null,

    City varchar(100) not null,

    State varchar(2) not null

    )

    insert into Customers

    select 'ABC','ABC Corporation','Boston','MA' union all

    select 'DEF','The DEF Foundation','New York City','NY'

    ... and we wish to also return each customers' name, city and state in our previous

    results. One way to do this is to simply add the Customers table to our existing

    join, and then add the customer columns to the SELECT clause. However, unless

    you add all of the customer columns to the GROUP BYas well, you will get an error

    message indicating that you need to either group or summarize all columns you

    wish to display. We aren't trying to calculate a COUNT() or a SUM() of Name, City

    and State, so it doesn't make sense to wrap those columns in an aggregateexpression. So, it appears that we must add them all to our GROUP BY clause to

    get the results we need:

    select

    o.Customer, c.customerName, c.City, c.State,

    count(*) as OrderCount,

  • 7/28/2019 How to Use GROUP by in SQL Server

    13/38

    sum(o.ShippingCost) as ShippingTotal, sum(d.ItemCount) as ItemCount,

    sum(d.OrderAmount) as OrderAmount

    from

    orders o

    inner join

    (select

    orderID, count(*) as ItemCount, sum(Amount) as OrderAmount

    from

    orderDetails

    group by

    orderID

    ) d

    on o.orderID = d.orderID

    inner join

    customers c on o.customer = c.customer

    group byo.customer, c.customerName, c.City, c.State

    Customer customerName City State OrderCount ShippingTotal

    ItemCount OrderAmount

    ---------- -------------------- --------------- ----- ----------- ------------- --------- -----------

    ABC ABC Corporation Boston MA 3 95.0000 6

    725.0000

    DEF The DEF Foundation New York City NY 2 20.0000 3

    475.0000

    (2 row(s) affected)

    Technically, that works, but it seems silly to list all of those customer columns in

    the GROUP BY... After all, we are just grouping on Customer, not on each of the

    customer's attributes, right?

    What's interesting is that the solution is something we already talked about and the

    same technique applies: Since Customer has a one-to-many relation with Orders,

    we know that joining Customers to Orders will result in duplicate rows per

    Customer, and thus all columns in the Customer table are duplicated in the results.

    You might notice that this is exactly the same scenario that applies when joiningOrders to OrderDetails. So, we handle this situation the same way! We simply

    summarize our Orders by Customer first, in a derived table, and then we join

    those results to the Customer table. This means that no columns from the

    Customer table will be dupicated at all, and there is no need to add them all to our

    GROUP BY expression. This keep our SQL clean, organized, and logically sound.

    So, our final results now look like this:

  • 7/28/2019 How to Use GROUP by in SQL Server

    14/38

    select

    c.Customer, c.customerName, c.City, c.State,

    o.OrderCount, o.ShippingTotal,

    o.ItemCount, o.OrderAmount

    from

    (

    select

    o.customer, count(*) as OrderCount,

    sum(o.ShippingCost) as ShippingTotal, sum(d.ItemCount) as ItemCount,

    sum(d.OrderAmount) as OrderAmount

    from

    orders o

    inner join

    (

    select

    orderID, count(*) as ItemCount, sum(Amount) as OrderAmount

    fromorderDetails

    group by

    orderID

    ) d

    on o.orderID = d.orderID

    group by o.customer

    ) o

    inner join

    customers c on o.customer = c.customer

    Customer customerName City State OrderCount ShippingTotalItemCount OrderAmount

    ---------- -------------------- --------------- ----- ----------- ------------- --------- -----------

    ABC ABC Corporation Boston MA 3 95.0000 6

    725.0000

    DEF The DEF Foundation New York City NY 2 20.0000 3

    475.0000

    (2 row(s) affected)

    Conclusion

    I hope this two part series helps a little bit with your understanding ofGROUP

    BYqueries. It is vital to identify and understand what the virtual primary key of a

    result set is when you join multiple tables, and to recognize which rows are

    duplicated or not. In addition, remember that COUNT(Distinct) can be useful,

    but SUM(Distinct) should very rarely, if ever, be used.

  • 7/28/2019 How to Use GROUP by in SQL Server

    15/38

    In general, if you find that values you need to SUM() have been duplicated,

    summarize the table causing those duplicates separately and join it in as a derived

    table. This will also allow you to break down your problem into smaller steps and

    test and validate the results of each step as you go.

    GROUP BYis a very powerful feature, but is also misunderstood and abused, andthe easiest way to leverage it is to carefully build your SQL from smaller, simpler

    parts into larger, more complicated solutions

    Joining to the Next Sequential Row

    By Paul Alconon 2 April 2008 | 21 Comments| Tags: Queries, SELECT

    One of the more obscure requirements that a developer may find themselves facingis the need to compare a row with its immediate sibling. One such case is when a

    list of values needs to be processed to produce a moving average or to smooth a

    sequence of statistical numbers where their order is important. For example,

    values lying along a time line. The solution is actually quite simple, but not

    immediately obvious.

    Problem

    Take a sequence of 8 integers 10, 25, 5, 15, 30, 9, 22, 29 in a single table thus:

    id stat period

    --- ------- --------

    1 10 1/1/2008

    2 25 2/1/2008

    3 5 3/1/2008

    4 15 4/1/2008

    5 30 5/1/2008

    http://www.sqlteam.com/author/paul-alconhttp://www.sqlteam.com/forums/topic.asp?TOPIC_ID=100121http://www.sqlteam.com/tag/sql-server-querieshttp://www.sqlteam.com/tag/selecthttp://www.sqlteam.com/author/paul-alconhttp://www.sqlteam.com/forums/topic.asp?TOPIC_ID=100121http://www.sqlteam.com/tag/sql-server-querieshttp://www.sqlteam.com/tag/select
  • 7/28/2019 How to Use GROUP by in SQL Server

    16/38

    6 9 6/1/2008

    7 22 7/1/2008

    8 29 8/1/2008

    We need to calculate the difference between each statistic and the next, thencalculate the mean value of the 'gaps.' It is important that the figures are

    compared in the right order to get a correct result. Firstly lets create a table and fill

    it with our sample data.

    createtable tbStats

    (

    id intidentity(1,1) primarykey,

    stat intnotnull,

    period datetime notnull

    )

    GO

    insertinto tbStats ( stat, period)

    select 10, convert(datetime, '20080101')

    unionall

    select 25, convert(datetime, '20080102')

    unionall

    select 5, convert(datetime, '20080103')

    unionall

    select 15, convert(datetime, '20080104')

    unionall

    select 30, convert(datetime, '20080105')unionall

    select 9, convert(datetime, '20080106')

    unionall

    select 22, convert(datetime, '20080107')

    unionall

    select 29, convert(datetime, '20080108')

    GO

    It's important to note that the records have been inserted in date order. Therefore,

    we know that the id column is in the same order as the period column. This

    alignment is important for our first solution to work correctly.

    Solution 1

    We need to join each record with it's subsequent row. We can do that using the

    ever flexible joining syntax, thanks to the fact that we know the id field is an

    integer sequence with no gaps. In the case where this is not guaranteed in your

  • 7/28/2019 How to Use GROUP by in SQL Server

    17/38

    target data, you can engineer it by transferring the required records into a

    temporary table or table variable first.

    select

    x.id xId,

    y.id yId,

    x.stat xStat,

    y.stat yStat

    from

    tbStats x

    leftjoin tbStats y on x.id + 1 = y.id

    orderby

    x.id

    xId yId xStat yStat

    ----------- ----------- ----------- -----------

    1 2 10 252 3 25 5

    3 4 5 15

    4 5 15 30

    5 6 30 9

    6 7 9 22

    7 8 22 29

    8 NULL 29 NULL

    (8 row(s) affected)

    By aliasing the table we can incorporate it into the SQL query twice, then join them

    together in a staggered fashion by adding 1 to the id of the first aliased table. The

    first record in the table has an id of 1. 1 + 1 = 2 so it will join on the row with id of

    2 in the second aliased table. And so on.

    Now it's simply a case of subtracting one from the other.

    select

    x.id xId,

    y.id yId,

    x.stat xStat,y.stat yStat,

    abs(x.stat - y.stat) gap

    from

    tbStats x

    leftjoin tbStats y on x.id + 1 = y.id

    orderby

    x.id

  • 7/28/2019 How to Use GROUP by in SQL Server

    18/38

    xId yId xStat yStat gap

    ----------- ----------- ----------- ----------- -----------

    1 2 10 25 15

    2 3 25 5 20

    3 4 5 15 104 5 15 30 15

    5 6 30 9 21

    6 7 9 22 13

    7 8 22 29 7

    8 NULL 29 NULL NULL

    (8 row(s) affected)

    We use the ABS function to ensure we always get positive integers as a result of

    the subtraction regardless of which side of the expression is the higher figure.

    Lastly we use the AVG function to get our final aggregated result.

    select

    avg(abs(x.stat - y.stat)) movingAvg

    from

    tbStats x

    leftjoin tbStats y on x.id + 1 = y.id

    where

    y.stat isnot null

    movingAvg

    -----------

    14

    (1 row(s) affected)

    Solution 2

    What if the record's ID and period fields are not in the same order? Lets refill our

    example table with some unordered data. When I describe the data as unordered, Iam referring to the fact that the id and period columns are not in alignment.

    Truncatetable tbStats

    GO

    insertinto tbStats ( stat, period)

  • 7/28/2019 How to Use GROUP by in SQL Server

    19/38

    select 5, convert(datetime, '20080103')

    unionall

    select 25, convert(datetime, '20080102')

    unionall

    select 15, convert(datetime, '20080104')

    unionallselect 9, convert(datetime, '20080106')

    unionall

    select 30, convert(datetime, '20080105')

    unionall

    select 22, convert(datetime, '20080107')

    unionall

    select 29, convert(datetime, '20080108')

    unionall

    select 10, convert(datetime, '20080101')

    GO

    createindex ix_tbStats_period on tbStats (period)

    GO

    In this situation another solution to staggering the rows is to create a user defined

    function to return the subsequent row. As this time we will be working on the

    period column, it is pertinent to create an index on that column. For the amount of

    data we are dealing with in our example it will be of no significance, but I would be

    negligent not to mention it here, if only in passing.

    CREATEFUNCTION dbo.Stagger(

    @period DATETIME

    )

    RETURNSINT

    AS

    BEGIN

    DECLARE @ResultVar INT

    SELECTTOP 1 @ResultVar = stat

    FROM tbStats

    WHERE period > @period ORDERBY period

    RETURN @ResultVar

    END

    GO

  • 7/28/2019 How to Use GROUP by in SQL Server

    20/38

    By using the TOP keyword and an ORDER BY clause, we can select the next

    consecutive date that occurs in the table after the date passed into the function as

    a parameter.

    select

    avg(abs(x.stat - dbo.Stagger(x.period))) movingAvg

    from

    tbStats x

    movingAvg

    -----------

    14

    (1 row(s) affected)

    Solution 3

    For those running SQL Server 2005 we have a third weapon in the armory for

    tackling this problem: APPLY. With APPLY there are two semantics that can be used

    to join a table valued function. CROSS and OUTER. OUTER will return all rows in

    the left hand table regardless of whether the table valued function returns rows or

    not (Similar to a left outer join) CROSS apply will only return left hand rows when

    there are also rows in the table valued function. We can use either in our solution.

    But, CROSS apply will have the neat outcome that the NULL data will be removed

    for the last record. We can make a new table valued function based on our previous

    one.

    CREATEFUNCTION dbo.StaggerTable

    (

    @period DATETIME

    )

    RETURNSTABLE

    AS

    RETURN

    SELECTTOP 1 id, stat

    FROM tbStats

    WHERE period > @period

    ORDERBY periodGO

    And alter our previous statement to include it using CROSS APPLY, which I think

    you'll agree looks much cleaner.

  • 7/28/2019 How to Use GROUP by in SQL Server

    21/38

    select

    avg(abs(x.stat - y.stat)) movingAvg

    from

    tbStats x

    cross apply dbo.StaggerTable(x.period) y

    movingAvg

    -----------

    14

    (1 row(s) affected)

    Performance Note

    Please check the performance carefully as your mileage can vary considerably withthese kinds of query -- particularly for solution #2. Running a user-defined function

    for every row in a result set can impact performance. Especially if they query in the

    UDF is anything other than a very simple query. Personally I used solution one as it

    gave me best advantage of using indexes and I had the luxury of a contiguous

    sequential key. Of the UDF solutions number three using The CROSS APPLY method

    is preferred and has been faster based on limited testing. Small data sets are your

    friend here.

    Conclusion

    So we have seen how SQL Server offers us plenty of flexibility in massaging ourstored data into viable meaningful results. Through joining on more sophisticated

    semantics beyond merely matching values as they are and/or leveraging user

    defined functions.

    Interview Questions inASP.NET,C#.NET,SQL Server,.NETFramework

    By: Suresh Dasari Oct 13, 2012

    Categories:Interview Questions

    Here I am posting the interview questions whatever i have faced in my interviewsI have searched for so many websites and gathered information from my friends toanswer the questions perfectly.

    i think these questions are very helpful for the people who are trying to get the job

    on .NETThe most common question for experience persons is

    http://www.aspdotnet-suresh.com/2010/05/interview-questions-in-aspnetcnetsql.htmlhttp://www.aspdotnet-suresh.com/2010/05/interview-questions-in-aspnetcnetsql.htmlhttp://www.aspdotnet-suresh.com/2010/05/interview-questions-in-aspnetcnetsql.htmlhttp://www.blogger.com/email-post.g?blogID=7805972021499203804&postID=6252394035406578724http://www.aspdotnet-suresh.com/search/label/Interview%20Questionshttp://www.aspdotnet-suresh.com/search/label/Interview%20Questionshttp://www.blogger.com/email-post.g?blogID=7805972021499203804&postID=6252394035406578724http://www.aspdotnet-suresh.com/2010/05/interview-questions-in-aspnetcnetsql.htmlhttp://www.aspdotnet-suresh.com/2010/05/interview-questions-in-aspnetcnetsql.htmlhttp://www.aspdotnet-suresh.com/2010/05/interview-questions-in-aspnetcnetsql.htmlhttp://www.aspdotnet-suresh.com/search/label/Interview%20Questions
  • 7/28/2019 How to Use GROUP by in SQL Server

    22/38

    Why would you like to change the company?

    1) I am looking for a more challenging career in a firm with a larger employee basesuch as yours.

    2) Keeping in mind my career goals, the time has come for me to move onto the

    next rung ofthe ladder and make a mark for myself. This can be achieved in a company like this.3) It is just a career move to enhance my knowledge in my own area of interest.

    After completion of this question only interview will go for further questions

    Difference between stored procedure and function

    1) Procedure can return zero or n values whereas function can return one value

    which is mandatory.2) Procedures can have input, output parameters for it whereas functions can have

    only input parameters.3) Procedure allows select as well as DML statement in it whereas function allows

    only select statement in it.

    4) Functions can be called from procedure whereas procedures cannot be called fromfunction.

    5) Exception can be handled by try-catch block in a procedure whereas try-catch

    block cannot be used in a function.6) We can go for transaction management in procedure whereas we can't go in

    function.7) Procedures cannot be utilized in a select statement whereas function can be

    embedded in a select statement.

    Difference between Abstract and Interface

    Abstract Class:

    -Abstract class provides a set of rules to implement next class-Rules will be provided through abstract methods

    -Abstract method does not contain any definition-While inheriting abstract class all abstract methods must be override

    -If a class contains at least one abstract method then it must be declared as anAbstract Class

    -Abstract classes cannot be instantiated (i.e. we cannot create objects), but areference can be created

    -Reference depends on child class objects memory-Abstract classes are also called as Partial abstract classes

    -Partial abstract class may contain functions with body and functions without body

    -If a class contains all functions without body then it is called as Fully AbstractClass (Interface)

    Interface:

    -If a class contains all abstract methods then that class is known as Interface-Interfaces support like multiple inheritance

    -In interface all methods r public abstract by default

  • 7/28/2019 How to Use GROUP by in SQL Server

    23/38

    -Interfaces r implementable-Interfaces cannot be instantiated, but a reference can be created

    Index types in SQL Server

    Clustered Index

    Only 1 allowed per table physically rearranges the data in the table to confirm to the

    index constraints for use on columns that are frequently searched for ranges of datafor use on columns with low selectivity.

    Non-Clustered Index

    Up to 249 allowed per table creates a separate list of key values with pointers to the

    location of the data in the data pages For use on columns that are searched forsingle values

    A clustered index is a special type of index that reorders the way records in the table

    are physically stored. Therefore table can have only one clustered index. The leafnodes of a clustered index contain the data pages. A non-clustered index is a special

    type of index in which the logical order of the index does not match the physicalstored order of the rows on disk. The leaf node of a non-clustered index does not

    consist of the data pages. Instead, the leaf nodes contain index rows.

    Included Column Index (New in SQL Server 2005)

    In SQL Server 2005, the functionality of non-clustered indexes is extended by adding

    non-key columns to the leaf level of the non-clustered index. Non-key columns canhelp to create cover indexes. By including non-key columns, you can create non-clustered indexes that cover more queries. The Database Engine does not consider

    non-key columns when calculating the number of index key columns or index keysize. Non-key columns can be included in non-clustered index to avoid exceeding the

    current index size limitations of a maximum of 16 key columns and a maximumindex key size of 900 bytes. Another advantage is that using non-key column in

    index we can have index data types not allowed as index key columns generally.

    In following example column Filename is varchar(400), which will increase the size ofthe index key bigger than it is allowed. If we still want to include in our cover index

    to gain performance we can do it by using the Keyword INCLUDE.

    USE AdventureWorks

    GOCREATE INDEX IX_Document_Title

    ON Production.Document (Title, Revision)

    INCLUDE (FileName)

  • 7/28/2019 How to Use GROUP by in SQL Server

    24/38

    Non-key columns can be included only in non-clustered indexes. Columns cant be

    defined in both the key column and they INCLUDE list. Column names cant berepeated in the INCLUDE list. Non-key columns can be dropped from a table only

    after the non-key index is dropped first. For Included Column Index to exist there

    must be at least one key column defined with a maximum of 16 key columns and1023 included columns.

    Avoid adding unnecessary columns. Adding too many index columns, key or non-key

    as they will affect negatively on performance. Fewer index rows will fit on a page.

    This could create I/O increases and reduced cache efficiency. More disk space will berequired to store the index. Index maintenance may increase the time that it takes

    to perform modifications, inserts, updates, or deletes, to the underlying table orindexed view.

    Another example to test:

    Create following Index on Database AdventureWorks in SQL SERVER 2005

    USE AdventureWorks

    GOCREATE NONCLUSTERED INDEX IX_Address_PostalCode

    ON Person.Address (PostalCode)INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID)

    GO

    Test the performance of following query before and after creating Index. Theperformance improvement is significant.

    SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCodeFROM Person.Address

    WHERE PostalCode BETWEEN '98000'AND '99999';

    GO

    Interview questions

    What are differences between Array list and Hash table?

    Ans: 1) Hash table store data as name, value pair. While in array only value is store.

    2) To access value from hash table, you need to pass name. While in array, to accessvalue, you need to pass index number.3) you can store different type of data in hash table, say int, string etc. while in

    array you can store only similar type of data.

    What are differences between system.stringbuilder and system.string?

  • 7/28/2019 How to Use GROUP by in SQL Server

    25/38

    The main difference is system.string is immutable and system.stringbuilder is amutable. Append keyword is used in string builder but not in system.string.

    Immutable means once we created we cannot modified. Suppose if we want givenew value to old value simply it will discarded the old value and it will create new

    instance in memory to hold the new value.

    What are the differences between Application object and session object?

    Ans: The session object is used to maintain the session of each user. If one userenter in to the application then they get session id if he leaves from the application

    then the session id is deleted. If they again enter in to the application they getdifferent session id.

    But for application object the id is maintained for whole application.

    What are the different types of indexes?

    Ans: Two types of indexes are there one is clustered index and non-clustered index

    How many types of memories are there in .net?

    Ans: Two types of memories are there in .net stack memory and heap memory

    Is it possible to set the session out time manually?

    Ans: Yes we can set the session out time manually in web.config.

    What are differences between function and stored procedure?

    Ans:

    1) Function returns only one value but procedure returns one or more than one

    value.

    2) Function can be utilized in select statements but that is not possible in procedure.

    3) Procedure can have an input and output parameters but function has only inputparameters only.

    4) Exceptions can be handled by try catch block in procedures but that is notpossible in function.

    What are the differences between Abstract and interface?

    Ans: 1) Abstract cannot be instantiated but we can inherit. Interface it cannot be

    inherit it can be instantiate2) Interface contain only declarations no definitions. Abstract contain declarations

    and definitions.3) The class which contains only abstract methods is interface class. A class which

    contains abstract method is called abstract class

  • 7/28/2019 How to Use GROUP by in SQL Server

    26/38

    4) Public is default access specifier for interface we dont have a chance to declareother specifiers. In abstract we have chance to declare with any access specifier

    Can you Explain Page lifecycle in .net?

    Can you Explain .NET architecture in .net?

    What is the difference between primary key and unique key with not null?

    Ans: There is no difference between primary key and unique key with not null.

    What is boxing and unboxing concepts in .net?

    Ans: Boxing is a process of converting value type into reference typeUnboxing is a process of converting reference type to value type.

    What are the differences between value type and reference type?

    Ans: Value type contain variable and reference type are notcontaining value directly

    in its memory.Memory is allocated in managed heap in reference type and in value type memory

    allocated in stack. Reference type ex-class value type-struct, enumeration

    Is it possible to host the website from desktop?

    Ans: Yes

    Why we go for page rendering in Asp.Net Page life cycle?

    Ans: Browser understands an only html control thats why in page rendering we willconvert the aspx controls into html controls.

    Write a sample query for self join?

    Ans: Select e1.ename, e2.empid from emp e1, emp e2 where e1.empid=e2.mgrid;

    Can we change the index of primary key on table?

    Ans: No

    How to change the name of the table or stored procedure in sql?

    Ans: sp_rename oldtablename newtablename

    For changing the column nameSp_rename tablename.[Oldcolumnname],newcolumnname,Column

  • 7/28/2019 How to Use GROUP by in SQL Server

    27/38

    Ex:sp_rename tblemp.first,namechange,Column

    How to find out which index is defined on table?

    Ans: sp_helpindex tablename

    Can you write the program to find the length of string without using libraryfunction?

    Ans: for (int i=0; str[i]!=\n; i++)

    {Count++;

    }

    What is the difference between scope_identity() and current_identity()?

    Ans: Scope_identity and current _identity both are similar and it will return the lastidentity value generated in the table.

    Scope_Identity will return the identity value in table that is currently in scope

    What are difference between GET and POST Methods?

    Ans:GET Method ():

    1) Data is appended to the URL.2) Data is not secret.

    3) It is a single call system4) Maximum data that can be sent is 256.5) Data transmission is faster

    6) this is the default method for many browsers

    POST Method ():

    1) Data is not appended to the URL.

    2) Data is Secret3) it is a two call system.

    4) There is no Limit on the amount of data. That is characters any amount of datacan be sent.

    5) Data transmission is comparatively slow.6) No default and should be explicitly specified.

    What are difference between truncate and delete?

    Ans: 1) Delete keep the lock over each row where Truncate keeps the lock on table

    not on all the row.

  • 7/28/2019 How to Use GROUP by in SQL Server

    28/38

    2) Counter of the Identity column is reset in Truncate where it is not reset in Delete.3) Trigger is not fired in Truncate where as trigger is fired in Delete.

    4) In TRUNCATE we cannot rollback.5) In DELETE we can rollback

    What is the difference Grid View and between Data Grid (Windows)?

    Ans:

    1) GridView Control Enables you to add sorting, paging and editing capabilitieswithout writing any code.

    2)GridView Control Automatically Supports paging by setting the PagerSettingProperty.The Page Setting Property supports four Modles

    a. Numeric(by default)

    b. Next Previousc. NumericFirstLast

    d. Next PreviousLast

    3)It is Used in asp.net4)GridView Supports RowUpdating and RowUpdated Events.

    5)GidView is Capable of Pre-Operations and Post-Operations.6)GridView Has EditTemplates for this control

    7)It has AutoFormat

    DataGrid(Windows)

    1)DataGid Control raises single Event for operations2)DataGird Supports the SortCommand Events that occur when a column is Soted.

    3)DataGrid Supports UpdataCommand Event that occurs when the UpdateButton isclicked for an item in the grid.

    4)DataGrid is used in Windows GUI Application.5)It doesnot have EditTemplates for this control

    6)It doesnot have AutoFormat

    If I write System.exit (0); at the end of the try block, will the finally blockstill execute?

    Ans: No in this case the finally block will not execute because when you say

    system.exit(0),the control immediately goes out of the program, and thus finally

    never executes.

    What are the different levels of State management in ASP.NET?

    Ans:

    State management is the process by which you maintain state and page informationover multiple requests for the same or different pages.

    There are 2 types State Management:

  • 7/28/2019 How to Use GROUP by in SQL Server

    29/38

    1. Client Side State ManagementThis stores information on the client's computer by embedding the information into a

    Web page, a uniform resource locator (url), or a cookie. The techniques available tostore the state information at the client end are listed down below:

    a. View State Asp.Net uses View State to track the values in the Controls. You can

    add custom values to the view state. It is used by the Asp.net page framework toautomatically save the values of the page and of each control just prior to rendering

    to the page. When the page is posted, one of the first tasks performed by pageprocessing is to restore view state.

    b. Control State If you create a custom control that requires view state to work

    properly, you should use control state to ensure other developers dont break yourcontrol by disabling view state.

    c. Hidden fields Like view state, hidden fields store data in an HTML form without

    displaying it in the user's browser. The data is available only when the form is

    processed.

    d. Cookies Cookies store a value in the user's browser that the browser sends withevery page request to the same server. Cookies are the best way to store state datathat must be available for multiple Web pages on a web site.

    e. Query Strings - Query strings store values in the URL that are visible to the user.

    Use query strings when you want a user to be able to e-mail or instant messagestate data with a URL.

    2. Server Side State Management

    a. Application State - Application State information is available to all pages,regardless of which user requests a page.

    b. Session State Session State information is available to all pages opened by auser during a single visit.

    Both application state and session state information is lost when the applicationrestarts. To persist user data between application restarts, you can store it using

    profile properties.

    Abstract Class:

    Abstract class is a class which cant be instantiate. Class should have Abstract keyword with the name. In any one of the method of class having abstract method with

    in it, then it should be define as abstract class. The class which derived the abstractclass should have definition of the abstract method. These classes which derived the

    abstract class and implement the abstract methods call concrete class.Abstract class may have the definition of function or may not. Below is the simple

    example of an abstract classpublic abstract alass AbstractStudent

    {String Roll

    {get;

    set;

  • 7/28/2019 How to Use GROUP by in SQL Server

    30/38

    }

    String FirstName{

    get;set;

    }

    String LastName{

    get;set;

    }

    Public String GetStudentDetails()

    {

    // Implementation of Method

    }

    public String SaveStudentDetails ()

    {// Implementation of Method

    }

    public abstract String CalculateWage();

    }So, the class having one abstract method so we need to mention the class as

    "abstract" .

    Difference between Abstract Class and Interface?

    Abstract class is a class which cant be instantiatedand which can have methods withdefinition as well as declaration also. This can be inherited.

    As for Example:

    public abstract class AbstractStudent

    {String Roll

    {get;

    set;}

    String FirstName

    {get;

    set;}

  • 7/28/2019 How to Use GROUP by in SQL Server

    31/38

    String LastName{

    get;set;

    }

    Public String GetStudentDetails(){

    // Implementation of Method}

    public String SaveStudentDetails ()

    {// Implementation of Method

    }

    public abstract String CalculateWage();

    }

    Interface can only contain the methods declaration and can be implemented in the

    class.

    As for Example:Public interface IStudnet

    {String Roll

    {get;

    set;

    }

    String FirstName

    {get;

    set;}

    String LastName

    {get;

    set;

    }

    String GetStudentDetails();

    String SaveStudentDetails ();}

    Below are the few main difference between Abstract Class and Interface

    a. In abstract class method can have definition as well as declaration also. But

    Interface should have only definition.

  • 7/28/2019 How to Use GROUP by in SQL Server

    32/38

    b. All the Methods are Public as default and dont have any access ModifierControls in interface, whereas for abstract class we can have access modifier for

    methods.c. Abstract class can have constructor or destructor, whereas interface not.

    d. Abstract class cant be part of multiple inheritance and we can implementmultiple interface.

    What do you mean by String objects are immutable?

    String objects are immutable as its state cannot be modified once created. Every

    time when we perform any operation like add, copy, replace, and case conversion orwhen we pass a string object as a parameter to a method a new object will be

    created.

    Example:String str = "ABC";

    str.Replace("A","X");

    Here Replace() method will not change data that "str" contains, instead a new string

    object is created to hold data "XBC" and the reference to this object is returned byReplace() method.

    So in order to point strto this object we need to write below line.

    str = str.Replace("A","X");Now the new object is assigned to the variable str. earlier object that was assigned

    to str will take care by garbage collector as this one is no longer in used.

    What is dll hell problem in .NET and how it will solve?

    Ans: Dll hell, is kind of conflict that occurred previously, due to the lack of versionsupportability of dll for (within) an application

    .NET Framework provides operating system with a global assembly cache. This cacheis a repository for all the .net components that are shared globally on a particular

    machine. When a .net component installed onto the machine, the global assemblycache looks at its version, its public key and its language information and creates a

    strong name for the component. The component is then registered in the repositoryand indexed by its strong name, so there is no confusion between the different

    versions of same component, or DLL

    What is a Partial class?

    Ans: Instead of defining an entire class, you can split the definition into multiple

    classes by using partial class keyword. When the application compiled, c# compilerwill group all the partial classes together and treat them as a single class. There are

    a couple of good reasons to use partial classes. Programmers can work on different

    parts of classes without needing to share same physical fileEx:

    Public partial class employee

  • 7/28/2019 How to Use GROUP by in SQL Server

    33/38

    {Public void somefunction()

    {}

    }Public partial class employee

    {Public void function ()

    {}

    }

    What is difference between constants, read-only and, static?

    Constants: The value cant be changed

    Read-only: The value will be initialized only once from the constructor of the class.

    Static: Value can be initialized once.

    What is the cross page post backing?

    Asp.Net 2.0 fixed this with built-in features that allowed us to easily send information

    from one page to another.

    Button control has property PostBackUrl that can be set to URL of any page in ourASP.Net WebSite where we want to transfer all form values to.

    Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows usto get reference to the Page object that initiated the postback (in other words to get

    the actual reference to the Page object of the aspx page on which user clicked the

    Submit button on a HTML form).

    So for example lets create two sample pages in our Web Application:

    SourcePage.aspx

    DestinationPage.aspx

    In SoucePage in Html form we will put two TextBox controls (one for First Name andone for Last Name) and one Button component and set its PostBackUrl property to

    "~/DestinationPage.aspx".

    SourcePage.aspx:

    FirstName:

    Last

    Name:

  • 7/28/2019 How to Use GROUP by in SQL Server

    34/38

    When our user clicks the Submit button, all the values from the HTML Form on

    SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also beable to get reference to the SourcePage.aspx in our DestinationPage with

    the PreviousPage property like this:

    So in our DestinationPage.aspx.cs code-behind we can easily access two TextBoxcontrols on SourcePage.aspx and show them in two label controls like this:

    protectedvoid Page_Load(object sender, EventArgs e){

    // first check if we had a cross page postback if( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )

    { Page previousPage = PreviousPage;

    TextBox firstName = (TextBox)previousPage.FindControl("FirstName"); TextBox lastName = (TextBox)previousPage.FindControl("LastName");

    // we can now use the values from TextBoxes and display them in two Label

    controls..labelFirstName.Text = firstName.Text;

    labelLastName.Text = lastName.Text;}

    }

    You probably noticed that we first checked ifPreviousPage property of current page

    (DestinationPage.aspx) is NOT NULL, this is done to avoid running our code in casethat user opens our DestinationPage.aspx directly, without running a cross page

    postback.

    Also here we checked the another PreviousPage propertycalled IsCrossPagePostBack to see if we really had a CrossPagePostback.

    (If Server.Transfer is used to redirect to this page, IsCrossPagePostBack property

    will be set to FALSE.

    TIP: We can be completely sure that we have a real CrossPagePostback ONLY IF:1. Page.PreviousPage is NOT NULL,2. PreviousPage.IsCrossPagePostback is trueThis important to check to avoid errors in code.

    Now this is very useful and i'm sure you are eager to use this in your next project.

    But wait, we are not over yet!

    Finding the controls on PreviousPage with FindControl method and type-casting themfrom object to their real type is a little messy.

    It feels like there must be a better solution for this!

    And here it is: We can use the directive in theheader of our DestinationPage.aspx like this

    to declare our previous page type, and then we can access Public properties of thePreviousPage without typecasting.

    Now all we need to do is to create some public properties on our SourcePage.aspx.csto expose data/Controls we want to the destionation page:

  • 7/28/2019 How to Use GROUP by in SQL Server

    35/38

    publicpartialclassSourcePage : System.Web.UI.Page{

    publicstring FormFirstName{

    get { return FirstName.Text; }}

    publicstring FormLastName

    { get { return LastName.Text; }

    }}

    And then we can change the Page_Load code in our DestinationPage.aspx to much

    cleaner code like this: protectedvoid Page_Load(object sender, EventArgs e)

    { // first check if we had a cross page postback

    if( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )

    { SourcePage prevPage = PreviousPage;

    // we can now use the values from textboxes and display them in two Labelcontrols..

    labelFirstName.Text = prevPage.FormFirstName;labelLastName.Text = prevPage.FormLastName;

    }}

    SourcePage type used in the code is offcourse name of the partial class defined is

    SourcePage.aspx.cs that inherits System.Web.UI.Page that is automaticallycreated for us when we created new WebForm in VisualStudio.

    This code is much cleaner and easier to follow, there is no ugly typecasting, just

    simple property values to use to retrieve the data from previous page.

    When should you use Abstract Class vs Interface while programming?

    Ans: When we want that sub class must implement all the methods of base class. In

    such a situation we will implement the interface. In the other hand when we wantonly some method of base class in our sub class then use base class as abstract

    class.

    What is the difference between application exception and system

    exception?

  • 7/28/2019 How to Use GROUP by in SQL Server

    36/38

    Ans: The difference between application exception and system exception is that

    system exceptions are thrown by CLR and application exceptions are thrown by

    applications.

    What is the difference between authorization and authentication?

    Ans: Authorization is a process of allowing or denying resources to particular user orrecord

    Declaration of authorization is

    Sometimes authorization allows the unauthorized persons at that time we will use

    Authentication means

    Authentication is a process where we identify the credentials of user i.e. username,

    password and create an identity to mention user as an authenticated.

    What is the use of n-tier architecture and 3-tier architecture?

    Check this article for 3-tier architecture 3 tier architecture example in asp.net

    How to get the version of the assembly?

    Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();

    What is the location of Global Assembly Cache on the system?

    Ans: c:\Windows\assembly

    What is the serialization?

    Ans: Serialization is a process of converting object into a stream of bites.

    http://www.aspdotnet-suresh.com/2010/05/introduction-to-3-tier-architecture-in_17.htmlhttp://www.aspdotnet-suresh.com/2010/05/introduction-to-3-tier-architecture-in_17.html
  • 7/28/2019 How to Use GROUP by in SQL Server

    37/38

    What is synchronization?

    Ans: The mechanism needed to block one thread access to the data. If the data isbeing accessed by another thread.

    Synchronization can be accessed by using system.monitor class

    A monitor class methods are enter, exit, pulse for this lock statement is also usedSuppose if we need to synchronize some data at that time we need to place thatdata in this block

    Lock{

    }Whatever the data has been placed into the lock block that data has been blocked

    What are the thread priority levels?

    Ans: Thread priority levels are five types

    0 - Zero level1 - Below Normal

    2 - Normal3 - Above Normal

    4 - HighestBy Default priority level is 2

    What is the difference between .tostring(), Convert.tostring()?

    Ans: The basic difference between them is Convert function handles NULLS while

    .ToString() does not it will throw a NULL reference exception error. So as a goodcoding

    practice using convert is always safe.

    What is Collation?

    Ans: Collation refers to a set of rules that determine how the data is sorted andcompared.

    What is the difference between Primary key and unique key?

    Ans: Primary key does not allow the null values but unique key allows one null

    value.Primary key will create clustered index on column but unique key will create non-

    clustered index by default.

    How many web.config files are there in 1 project?

  • 7/28/2019 How to Use GROUP by in SQL Server

    38/38

    Ans: There might be multiple web.config files for a single project depending on thehierarchy of folders inside the root folder of the project, so for each folder we can

    use one web.config file

    What is the difference between throw and throw ex?What is the difference between view state and hidden field?

    Ans: viewstate is secured hidden field is insecure

    Viewstate will store large amount of data but hidden filed will store small amount ofdata.

    What is the difference between binary serialization and xml serialization?

    What is the Difference between read only and constant variables?

    Ans: Read only can assign the values at runtime only.Constant will assign the values at compile time only.

    We cannot modify the both variable values.

    What is static keyword in .Net?

    Ans: Static is same as constant variable but we can change the value of staticvariable and we can access the variables without creating any instances

    What is the use of business logic layer in 3-tier architecture in .net?

    Ans: Though a web site could talk to the data access layer directly, it usually goesthrough another layer called the business layer. The business layer is vital in that it

    validates the input conditions before calling a method from the data layer. Thisensures the data input is correct before proceeding, and can often ensure that theoutputs are correct as well. This validation of input is called business rules, meaning

    the rules that the business layer uses to make judgments about the data.

    However, business rules dont only apply to data validation; these rules apply to any

    calculations or any other action that takes place in the business layer. Normally, itsbest to put as much logic as possible in the business layer, which makes this logic

    reusable across applications.

    One of the best reasons for reusing logic is that applications that start off smallusually grow in functionality. For instance, a company begins to develop a web site,and as they realize their business needs, they later decide to add a smart client

    application and windows service to supplement the web site. The business layer

    helps move logic to a central layer for maximum reusability.