SlideShare uma empresa Scribd logo
1 de 4
Baixar para ler offline
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]

Mais conteúdo relacionado

Destaque

MS SQL SERVER: Creating Views
MS SQL SERVER: Creating ViewsMS SQL SERVER: Creating Views
MS SQL SERVER: Creating Viewssqlserver content
 
Consultas en MS SQL Server 2012
Consultas en MS SQL Server 2012Consultas en MS SQL Server 2012
Consultas en MS SQL Server 2012CarlosFloresRoman
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guidelineSidney Chen
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueriesecomputernotes
 
Sub-queries,Groupby and having in SQL
Sub-queries,Groupby and having in SQLSub-queries,Groupby and having in SQL
Sub-queries,Groupby and having in SQLVikash Sharma
 
Triggers-Sequences-SQL
Triggers-Sequences-SQLTriggers-Sequences-SQL
Triggers-Sequences-SQLPatrick Seery
 
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1 "Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1 Andriy Krayniy
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 
Sql query analyzer & maintenance
Sql query analyzer & maintenanceSql query analyzer & maintenance
Sql query analyzer & maintenancenspyrenet
 
SQL Server - Using Tools to Analyze Query Performance
SQL Server - Using Tools to Analyze Query PerformanceSQL Server - Using Tools to Analyze Query Performance
SQL Server - Using Tools to Analyze Query PerformanceMarek Maśko
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptFramgia Vietnam
 
Database Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyDatabase Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyBoris Hristov
 

Destaque (20)

Sql db optimization
Sql db optimizationSql db optimization
Sql db optimization
 
Joins SQL Server
Joins SQL ServerJoins SQL Server
Joins SQL Server
 
MS SQL SERVER: Creating Views
MS SQL SERVER: Creating ViewsMS SQL SERVER: Creating Views
MS SQL SERVER: Creating Views
 
Consultas en MS SQL Server 2012
Consultas en MS SQL Server 2012Consultas en MS SQL Server 2012
Consultas en MS SQL Server 2012
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guideline
 
Sql xp 04
Sql xp 04Sql xp 04
Sql xp 04
 
Statistics
StatisticsStatistics
Statistics
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
 
Sub-queries,Groupby and having in SQL
Sub-queries,Groupby and having in SQLSub-queries,Groupby and having in SQL
Sub-queries,Groupby and having in SQL
 
Locking in SQL Server
Locking in SQL ServerLocking in SQL Server
Locking in SQL Server
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
 
Triggers-Sequences-SQL
Triggers-Sequences-SQLTriggers-Sequences-SQL
Triggers-Sequences-SQL
 
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1 "Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Locking And Concurrency
Locking And ConcurrencyLocking And Concurrency
Locking And Concurrency
 
Sql query analyzer & maintenance
Sql query analyzer & maintenanceSql query analyzer & maintenance
Sql query analyzer & maintenance
 
SQL Server - Using Tools to Analyze Query Performance
SQL Server - Using Tools to Analyze Query PerformanceSQL Server - Using Tools to Analyze Query Performance
SQL Server - Using Tools to Analyze Query Performance
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
Database Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyDatabase Transactions and SQL Server Concurrency
Database Transactions and SQL Server Concurrency
 

Semelhante a Using grouping sets in sql server 2008 tech republic

Using hash fields in sql server tech republic
Using hash fields in sql server   tech republicUsing hash fields in sql server   tech republic
Using hash fields in sql server tech republicKaing Menglieng
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republicKaing Menglieng
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
Filtered indexes in sql server 2008 tech republic
Filtered indexes in sql server 2008   tech republicFiltered indexes in sql server 2008   tech republic
Filtered indexes in sql server 2008 tech republicKaing Menglieng
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copyMustafa EL-Masry
 
Using object dependencies in sql server 2008 tech republic
Using object dependencies in sql server 2008   tech republicUsing object dependencies in sql server 2008   tech republic
Using object dependencies in sql server 2008 tech republicKaing Menglieng
 
How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?loginworks software
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012Eduardo Castro
 
An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008Klaudiia Jacome
 
Columnstore improvements in SQL Server 2016
Columnstore improvements in SQL Server 2016Columnstore improvements in SQL Server 2016
Columnstore improvements in SQL Server 2016Niko Neugebauer
 
How do i... reseed a sql server identity column tech_republic
How do i... reseed a sql server identity column    tech_republicHow do i... reseed a sql server identity column    tech_republic
How do i... reseed a sql server identity column tech_republicKaing Menglieng
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republicKaing Menglieng
 
MS SQL SERVER: Microsoft time series algorithm
MS SQL SERVER: Microsoft time series algorithmMS SQL SERVER: Microsoft time series algorithm
MS SQL SERVER: Microsoft time series algorithmsqlserver content
 
MS SQL SERVER: Time series algorithm
MS SQL SERVER: Time series algorithmMS SQL SERVER: Time series algorithm
MS SQL SERVER: Time series algorithmDataminingTools Inc
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesAshwin Dinoriya
 

Semelhante a Using grouping sets in sql server 2008 tech republic (20)

Using hash fields in sql server tech republic
Using hash fields in sql server   tech republicUsing hash fields in sql server   tech republic
Using hash fields in sql server tech republic
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republic
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
Filtered indexes in sql server 2008 tech republic
Filtered indexes in sql server 2008   tech republicFiltered indexes in sql server 2008   tech republic
Filtered indexes in sql server 2008 tech republic
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copy
 
Using object dependencies in sql server 2008 tech republic
Using object dependencies in sql server 2008   tech republicUsing object dependencies in sql server 2008   tech republic
Using object dependencies in sql server 2008 tech republic
 
How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008
 
Columnstore improvements in SQL Server 2016
Columnstore improvements in SQL Server 2016Columnstore improvements in SQL Server 2016
Columnstore improvements in SQL Server 2016
 
How do i... reseed a sql server identity column tech_republic
How do i... reseed a sql server identity column    tech_republicHow do i... reseed a sql server identity column    tech_republic
How do i... reseed a sql server identity column tech_republic
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republic
 
MS SQL SERVER: Microsoft time series algorithm
MS SQL SERVER: Microsoft time series algorithmMS SQL SERVER: Microsoft time series algorithm
MS SQL SERVER: Microsoft time series algorithm
 
MS SQL SERVER: Time series algorithm
MS SQL SERVER: Time series algorithmMS SQL SERVER: Time series algorithm
MS SQL SERVER: Time series algorithm
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
 

Mais de Kaing Menglieng

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

Mais de Kaing Menglieng (20)

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