SlideShare a Scribd company logo
Using Grouping Sets in SQL Server 2008 | TechRepublic



   ZDNet Asia     SmartPlanet    TechRepublic                                                                                Log In   Join TechRepublic   FAQ   Go Pro!




                                                    Blogs    Downloads        Newsletters       Galleries       Q&A   Discussions     News
                                                Research Library


     IT Management              Development         IT Support       Data Center         Networks         Security




     Home / Blogs / The Enterprise Cloud                                                  Follow this blog:

     The Enterprise Cloud


     Using Grouping Sets in SQL
     Server 2008
     By Tim Chapman
     October 3, 2008, 8:23 AM PDT

     Takeaway: A neat new feature in SQL Server 2008 is the GROUPING SETS clause, which
     allows you to easily specify combinations of field groupings in your queries to see different levels of
     aggregated data. Today we’ll look at how you can use the new SQL Server 2008 GROUPING
     SETS clause to aggregate your data.



     GROUP BY
     The GROUP BY clause is a SQL language construct used to priovide summary data for column
     returned in a SELECT statement. This functionality groups values from specified fields together,
     providing a single record of distinct values for each group. To illustrate the how GROUP BY
     works, lets look at an example. Use the script below to create and load the SalesHistory table.

     IF OBJECT_ID('SalesHistory')>0

     DROP TABLE SalesHistory;

     GO

     CREATE TABLE [dbo].[SalesHistory]

     (    [SaleID] [int] IDENTITY(1,1) NOT NULL     PRIMARY KEY,

          [Product] [char] (150) NULL,

          [SaleDate] [datetime] NULL,

          [SalePrice] [money] NULL

     )

     GO

     DECLARE @i SMALLINT

     SET @i = 1

     WHILE (@i <=100)

     BEGIN      INSERT INTO SalesHistory

          (Product, SaleDate, SalePrice)

          VALUES ('Computer', DATEADD(mm, @i, '3/11/1919'), DATEPART(ms, GETDATE()) + (@i + 57))

          INSERT INTO SalesHistory

          (Product, SaleDate, SalePrice)




http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]
Using Grouping Sets in SQL Server 2008 | TechRepublic

           VALUES ('BigScreen', DATEADD(mm, @i, '3/11/1927'), DATEPART(ms, GETDATE()) + (@i + 13))

           INSERT INTO SalesHistory

           (Product, SaleDate, SalePrice)

           VALUES ('PoolTable', DATEADD(mm, @i, '3/11/1908'), DATEPART(ms, GETDATE()) + (@i + 29))

           SET @i = @i + 1

     END

     I can use the GROUP by clause to retrieve the average SalePrice per Product.

     SELECT Product, AVG(SalePrice) AS AverageSalePrice

     FROM SalesHistory

     GROUP BY Product

     Notice that the GROUP BY clause returns a distinct Product list, followed by the average of each
     SalePrice value.

     The only drawback of the GROUP BY clause is that it only really allows you to specify
     aggregations for a single set of database columns. The new SQL Server 2008 GROUPING SETS
     clause expands upon the GROUP BY functionality allowing you to specify different field
     combinations to return aggregate data.

     GROUPING SETS

     This functionality can enhance reporting requirements and data analysis by allowing you to retrieve
     aggregation data through one statement, rather than several distinct queries. GROUPING SETS
     also allows for “Grand total” data for the entire set of data, or just for sections of aggregations.

     The following query uses the GROUPING SETS clause on the SalesHistory table. This query
     returns 2 different sets of aggregations; one at the Product level, and a “Grand total” level, denoted
     by the () in the GROUPING SETS clause.

     SELECT Product, SUM(SalePrice) AS TotalSales, COUNT(*) AS SaleCount

     FROM SalesHistory

     GROUP BY GROUPING SETS((Product),())

     ORDER BY Product DESC, TotalSales DESC, SaleCount DESC

     Notice the last row returned in the above screenshot. This is the “Grant total” record I mentioned
     above.

     In the following query, I use three separate field sets in my GROUPING SETS clause. Doing so
     create three totally different sets of aggregations; one by Product, one by the SalesTier (calculated
     via a subquery), and one “Grand total” column. Note that the order in which the grouping sets
     appear in the GROUPING SETS clause is not important.

     SELECT

     Product, SalesTier, TotalSales = SUM(SalePrice), AverageSalePrice = AVG(SalePrice)

     FROM (

     SELECT

     Product,

     SalesTier =

              CASE             WHEN SalePrice BETWEEN 0 AND 500 THEN 'Tier 1'

                      WHEN SalePrice BETWEEN 501 AND 750 THEN 'Tier 2'

                      WHEN SalePrice BETWEEN 751 AND 1000 THEN 'Tier 3'

                      WHEN SalePrice > 1000 THEN 'Tier 4'

              END,

     SalePrice

     FROM SalesHistory

     ) a

     GROUP BY




http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]
Using Grouping Sets in SQL Server 2008 | TechRepublic

              GROUPING SETS((Product), (SalesTier), ())

     ORDER BY Product DESC, SalesTier DESC

     You can achieve the same results as the above query using typical TSQL constructs, but it is
     much more cumbersome to do so, as I show in the following script.

     IF OBJECT_ID('tempdb..#SalesResults') IS NOT NULL

     DROP TABLE #SalesResults

     CREATE TABLE #SalesResults

     (

              Product VARCHAR(10),

             SalesTier
     VARCHAR(10),
     Next Time

              TotalSales MONEY,

              AverageSalePrice MONEY

     )

     INSERT INTO #SalesResults(Product, SalesTier, TotalSales, AverageSalePrice)

     SELECT

              Product, NULL, SUM(SalePrice), AVG(SalePrice)

     FROM

              SalesHistory

     GROUP BY Product

     UNION ALL

     SELECT

              NULL,

              SalesTier,

              SUM(SalePrice),

              AVG(SalePrice)

     FROM

     (

              SELECT

              SalesTier =

                       CASE

                                WHEN SalePrice BETWEEN 0 AND 500 THEN 'Tier 1'

                                WHEN SalePrice BETWEEN 501 AND 750 THEN 'Tier 2'

                                WHEN SalePrice BETWEEN 751 AND 1000 THEN 'Tier 3'

                                WHEN SalePrice > 1000 THEN 'Tier 4'

                       END,

              SalePrice

              FROM SalesHistory

     ) a

     GROUP BY SalesTier

     UNION ALL

     SELECT

              NULL, NULL, SUM(SalePrice), AVG(SalePrice)

     FROM SalesHistory

     SELECT *

     FROM #SalesResults

     Next Time



http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]
Using Grouping Sets in SQL Server 2008 | TechRepublic

     Today I took a look at the usefulness of the new GROUPING SETS clause in SQL Server 2008.
     The results of the GROUPING SETS clause can be achived in other ways, but it takes more
     programming work to do so. Next time I will take a look at SQL Server 2008 enhancements to the
     CUBE and ROLLUP; two constructs that can produce similar results to the GROUPING SETS
     clause, but in a different manner.


     Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free
     newsletters.




                    About Tim Chapman
                        Full Bio    Contact




                   Take a stance on virtual                      Will you evaluate Microsoft
                   machine time sync                             Hyper-V Server 2008?




         2            Join the conversation!                                              Add Your Opinion
      Comments        Follow via:



      Staff Picks      Top Rated      Most Recent       My Contacts                              See All Comments




                       RE: Using Grouping Sets in SQL Server 2008                                      0
                       chapman.tim@... 7th Oct 2008                                                  Votes



             Looks to be...thanks for noticing. I'll get with TR to get them posted.


                 View in thread




                       Missing screen shots?                                                           0
                       MikeSQLDBA 6th Oct 2008                                                       Votes



             Interesting article, but are the screen shots missing?


                 View in thread




                                                 See all comments



     Join the TechRepublic Community and join the conversation! Signing-up is
     free and quick, Do it now, we want to hear your opinion.

       Join        Login




http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]

More Related Content

PDF
Using sql server 2008's merge statement tech republic
PDF
Understand when to use user defined functions in sql server tech-republic
PPT
Creating other schema objects
DOCX
database-querry-student-note
PDF
Powerful Explain in MySQL 5.6
PPT
Sql views
PDF
TSQL Coding Guidelines
PPT
Mysql Ppt
Using sql server 2008's merge statement tech republic
Understand when to use user defined functions in sql server tech-republic
Creating other schema objects
database-querry-student-note
Powerful Explain in MySQL 5.6
Sql views
TSQL Coding Guidelines
Mysql Ppt

Viewers also liked (20)

PDF
Sql db optimization
PPTX
MS SQL SERVER: Creating Views
PPTX
Consultas en MS SQL Server 2012
PPT
Sql tuning guideline
PPS
Sql xp 04
PPTX
Statistics
PPT
e computer notes - Subqueries
PPTX
Sub-queries,Groupby and having in SQL
PPSX
Locking in SQL Server
PPT
Review of SQL
RTF
Triggers-Sequences-SQL
PDF
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
PPT
Lecture 4. MS SQL. DML Triggers
PPT
Locking And Concurrency
PPTX
Sql query analyzer & maintenance
PDF
SQL Server - Using Tools to Analyze Query Performance
PPTX
View, Store Procedure & Function and Trigger in MySQL - Thaipt
PPT
SQL subquery
PPTX
Database Transactions and SQL Server Concurrency
Sql db optimization
MS SQL SERVER: Creating Views
Consultas en MS SQL Server 2012
Sql tuning guideline
Sql xp 04
Statistics
e computer notes - Subqueries
Sub-queries,Groupby and having in SQL
Locking in SQL Server
Review of SQL
Triggers-Sequences-SQL
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
Lecture 4. MS SQL. DML Triggers
Locking And Concurrency
Sql query analyzer & maintenance
SQL Server - Using Tools to Analyze Query Performance
View, Store Procedure & Function and Trigger in MySQL - Thaipt
SQL subquery
Database Transactions and SQL Server Concurrency
Ad

Similar to Using grouping sets in sql server 2008 tech republic (20)

PDF
Using hash fields in sql server tech republic
PDF
Avoiding cursors with sql server 2005 tech republic
PDF
See sql server graphical execution plans in action tech republic
PDF
Filtered indexes in sql server 2008 tech republic
DOCX
Create column store index on all supported tables in sql server 2014 copy
PDF
Using object dependencies in sql server 2008 tech republic
PDF
How to work with Subquery in Data Mining?
PPTX
TSQL in SQL Server 2012
PDF
Using T-SQL
PDF
Oracle SQL Basics
PPT
PPT
Beg sql
DOCX
An introduction to new data warehouse scalability features in sql server 2008
PDF
Columnstore improvements in SQL Server 2016
PDF
How do i... reseed a sql server identity column tech_republic
PPT
Introduction to Threading in .Net
PPTX
Training on Microsoft SQL Server(older version).pptx
PDF
Introduction to change data capture in sql server 2008 tech republic
PPTX
MS SQL SERVER: Microsoft time series algorithm
PPTX
MS SQL SERVER: Time series algorithm
Using hash fields in sql server tech republic
Avoiding cursors with sql server 2005 tech republic
See sql server graphical execution plans in action tech republic
Filtered indexes in sql server 2008 tech republic
Create column store index on all supported tables in sql server 2014 copy
Using object dependencies in sql server 2008 tech republic
How to work with Subquery in Data Mining?
TSQL in SQL Server 2012
Using T-SQL
Oracle SQL Basics
Beg sql
An introduction to new data warehouse scalability features in sql server 2008
Columnstore improvements in SQL Server 2016
How do i... reseed a sql server identity column tech_republic
Introduction to Threading in .Net
Training on Microsoft SQL Server(older version).pptx
Introduction to change data capture in sql server 2008 tech republic
MS SQL SERVER: Microsoft time series algorithm
MS SQL SERVER: Time series algorithm
Ad

More from Kaing Menglieng (20)

PDF
What is your sql server backup strategy tech_republic
PDF
Sql server indexed views speed up your select queries part 1 - code-projec
PDF
Sql server – query optimization – remove bookmark lookup – remove rid lookup
PDF
Sql server common interview questions and answers
PDF
Sql server common interview questions and answers page 6
PDF
Sql server common interview questions and answers page 5
PDF
Sql server common interview questions and answers page 4
PDF
Sql server common interview questions and answers page 2
PDF
Sql server – 2008 – hardware and software requirements for installing sql se
PDF
Speeding up queries with semi joins and anti-joins
PDF
Speed up sql
PDF
Speed up sql server apps - visual studio magazine
PDF
Reviewing sql server permissions tech republic
PDF
Query optimization how to search millions of record in sql table faster -
PDF
Optimize sql server queries with these advanced tuning techniques tech repu
PDF
New date datatypes in sql server 2008 tech republic
PDF
Introduction to policy based management in sql server 2008 tech-republic
PDF
How to import an excel file into sql server 2005 using integration services
PDF
How do i... query foreign data using sql server's linked servers tech_repu
PDF
Help! my sql server log file is too big!!! tech republic
What is your sql server backup strategy tech_republic
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server common interview questions and answers
Sql server common interview questions and answers page 6
Sql server common interview questions and answers page 5
Sql server common interview questions and answers page 4
Sql server common interview questions and answers page 2
Sql server – 2008 – hardware and software requirements for installing sql se
Speeding up queries with semi joins and anti-joins
Speed up sql
Speed up sql server apps - visual studio magazine
Reviewing sql server permissions tech republic
Query optimization how to search millions of record in sql table faster -
Optimize sql server queries with these advanced tuning techniques tech repu
New date datatypes in sql server 2008 tech republic
Introduction to policy based management in sql server 2008 tech-republic
How to import an excel file into sql server 2005 using integration services
How do i... query foreign data using sql server's linked servers tech_repu
Help! my sql server log file is too big!!! tech republic

Using grouping sets in sql server 2008 tech republic

  • 1. Using Grouping Sets in SQL Server 2008 | TechRepublic ZDNet Asia SmartPlanet TechRepublic Log In Join TechRepublic FAQ Go Pro! Blogs Downloads Newsletters Galleries Q&A Discussions News Research Library IT Management Development IT Support Data Center Networks Security Home / Blogs / The Enterprise Cloud Follow this blog: The Enterprise Cloud Using Grouping Sets in SQL Server 2008 By Tim Chapman October 3, 2008, 8:23 AM PDT Takeaway: A neat new feature in SQL Server 2008 is the GROUPING SETS clause, which allows you to easily specify combinations of field groupings in your queries to see different levels of aggregated data. Today we’ll look at how you can use the new SQL Server 2008 GROUPING SETS clause to aggregate your data. GROUP BY The GROUP BY clause is a SQL language construct used to priovide summary data for column returned in a SELECT statement. This functionality groups values from specified fields together, providing a single record of distinct values for each group. To illustrate the how GROUP BY works, lets look at an example. Use the script below to create and load the SalesHistory table. IF OBJECT_ID('SalesHistory')>0 DROP TABLE SalesHistory; GO CREATE TABLE [dbo].[SalesHistory] ( [SaleID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, [Product] [char] (150) NULL, [SaleDate] [datetime] NULL, [SalePrice] [money] NULL ) GO DECLARE @i SMALLINT SET @i = 1 WHILE (@i <=100) BEGIN INSERT INTO SalesHistory (Product, SaleDate, SalePrice) VALUES ('Computer', DATEADD(mm, @i, '3/11/1919'), DATEPART(ms, GETDATE()) + (@i + 57)) INSERT INTO SalesHistory (Product, SaleDate, SalePrice) http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]
  • 2. Using Grouping Sets in SQL Server 2008 | TechRepublic VALUES ('BigScreen', DATEADD(mm, @i, '3/11/1927'), DATEPART(ms, GETDATE()) + (@i + 13)) INSERT INTO SalesHistory (Product, SaleDate, SalePrice) VALUES ('PoolTable', DATEADD(mm, @i, '3/11/1908'), DATEPART(ms, GETDATE()) + (@i + 29)) SET @i = @i + 1 END I can use the GROUP by clause to retrieve the average SalePrice per Product. SELECT Product, AVG(SalePrice) AS AverageSalePrice FROM SalesHistory GROUP BY Product Notice that the GROUP BY clause returns a distinct Product list, followed by the average of each SalePrice value. The only drawback of the GROUP BY clause is that it only really allows you to specify aggregations for a single set of database columns. The new SQL Server 2008 GROUPING SETS clause expands upon the GROUP BY functionality allowing you to specify different field combinations to return aggregate data. GROUPING SETS This functionality can enhance reporting requirements and data analysis by allowing you to retrieve aggregation data through one statement, rather than several distinct queries. GROUPING SETS also allows for “Grand total” data for the entire set of data, or just for sections of aggregations. The following query uses the GROUPING SETS clause on the SalesHistory table. This query returns 2 different sets of aggregations; one at the Product level, and a “Grand total” level, denoted by the () in the GROUPING SETS clause. SELECT Product, SUM(SalePrice) AS TotalSales, COUNT(*) AS SaleCount FROM SalesHistory GROUP BY GROUPING SETS((Product),()) ORDER BY Product DESC, TotalSales DESC, SaleCount DESC Notice the last row returned in the above screenshot. This is the “Grant total” record I mentioned above. In the following query, I use three separate field sets in my GROUPING SETS clause. Doing so create three totally different sets of aggregations; one by Product, one by the SalesTier (calculated via a subquery), and one “Grand total” column. Note that the order in which the grouping sets appear in the GROUPING SETS clause is not important. SELECT Product, SalesTier, TotalSales = SUM(SalePrice), AverageSalePrice = AVG(SalePrice) FROM ( SELECT Product, SalesTier = CASE WHEN SalePrice BETWEEN 0 AND 500 THEN 'Tier 1' WHEN SalePrice BETWEEN 501 AND 750 THEN 'Tier 2' WHEN SalePrice BETWEEN 751 AND 1000 THEN 'Tier 3' WHEN SalePrice > 1000 THEN 'Tier 4' END, SalePrice FROM SalesHistory ) a GROUP BY http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]
  • 3. Using Grouping Sets in SQL Server 2008 | TechRepublic GROUPING SETS((Product), (SalesTier), ()) ORDER BY Product DESC, SalesTier DESC You can achieve the same results as the above query using typical TSQL constructs, but it is much more cumbersome to do so, as I show in the following script. IF OBJECT_ID('tempdb..#SalesResults') IS NOT NULL DROP TABLE #SalesResults CREATE TABLE #SalesResults ( Product VARCHAR(10), SalesTier VARCHAR(10), Next Time TotalSales MONEY, AverageSalePrice MONEY ) INSERT INTO #SalesResults(Product, SalesTier, TotalSales, AverageSalePrice) SELECT Product, NULL, SUM(SalePrice), AVG(SalePrice) FROM SalesHistory GROUP BY Product UNION ALL SELECT NULL, SalesTier, SUM(SalePrice), AVG(SalePrice) FROM ( SELECT SalesTier = CASE WHEN SalePrice BETWEEN 0 AND 500 THEN 'Tier 1' WHEN SalePrice BETWEEN 501 AND 750 THEN 'Tier 2' WHEN SalePrice BETWEEN 751 AND 1000 THEN 'Tier 3' WHEN SalePrice > 1000 THEN 'Tier 4' END, SalePrice FROM SalesHistory ) a GROUP BY SalesTier UNION ALL SELECT NULL, NULL, SUM(SalePrice), AVG(SalePrice) FROM SalesHistory SELECT * FROM #SalesResults Next Time http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]
  • 4. Using Grouping Sets in SQL Server 2008 | TechRepublic Today I took a look at the usefulness of the new GROUPING SETS clause in SQL Server 2008. The results of the GROUPING SETS clause can be achived in other ways, but it takes more programming work to do so. Next time I will take a look at SQL Server 2008 enhancements to the CUBE and ROLLUP; two constructs that can produce similar results to the GROUPING SETS clause, but in a different manner. Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free newsletters. About Tim Chapman Full Bio Contact Take a stance on virtual Will you evaluate Microsoft machine time sync Hyper-V Server 2008? 2 Join the conversation! Add Your Opinion Comments Follow via: Staff Picks Top Rated Most Recent My Contacts See All Comments RE: Using Grouping Sets in SQL Server 2008 0 chapman.tim@... 7th Oct 2008 Votes Looks to be...thanks for noticing. I'll get with TR to get them posted. View in thread Missing screen shots? 0 MikeSQLDBA 6th Oct 2008 Votes Interesting article, but are the screen shots missing? View in thread See all comments Join the TechRepublic Community and join the conversation! Signing-up is free and quick, Do it now, we want to hear your opinion. Join Login http://www.techrepublic.com/blog/datacenter/using-grouping-sets-in-sql-server-2008/456[08/29/2012 3:43:37 PM]