How the grouping set works in Sql2008

  • Can anyone tell me how exactly grouping set works in sql 2008.how it is different from group by clause.

  • You can use GROUP BY additionally with GROUPING SETS.

    If you've been useing GROUP BY for a number of columns, now imagine those columns as sets, and everything is the same. When you use sets to make the groupation you have to add the GROUPING SETS as reserved words.

    For example, the following select using GROUPING SETS

    SELECT Region, Department, avg(sal) AverageSalary

    from tblEmployee

    Group BY

    GROUPING SETS

    (

    (Region, Department)

    /*

    (Region),

    (Department) ,

    ()

    */

    )

    is equal to the following with only GROUP BY

    SELECT Region, Department, avg(sal) AverageSalary

    from tblEmployee

    Group BY

    Region, Department

    Regards,

    IgorMi

    Igor Micev,My blog: www.igormicev.com

  • Why should one use grouping sets when group by is available .how does it help?

  • sej2008 (12/8/2013)


    Why should one use grouping sets when group by is available .how does it help?

    GROUPING SETS is less frequently used, but sometimes it can be useful if you're aware of its usefulness.

    For example, the result set of this query will be first grouped by the grouping set (Region, Department), and then by City.

    SELECT Region, Department, avg(sal) AverageSalary

    from tblEmployee

    Group BY

    GROUPING SETS

    (

    (Region, Department),

    (City)

    )

    In this case the above select will not return the same ordered result set as

    SELECT Region, Department, avg(sal) AverageSalary

    from tblEmployee

    Group BY

    Region, Department, City

    Having got the example from the previous post, now you should have understood grouping sets...

    Regards,

    IgorMi

    Igor Micev,My blog: www.igormicev.com

  • You can see some results and experiment with queries given in this link http://technet.microsoft.com/en-us/library/bb522495(v=sql.105).aspx

    Igor Micev,My blog: www.igormicev.com

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply