Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

How to use ROLLUP with GROUP BY clause in SQL Server

$
0
0
As we know GROUP BY clause use to groups the result set into summary. For example pleas execute the following query.

I am creating a productSales table which have sales data of product for country.


CREATETABLE#ProductSales
(
       IDINTIDENTITY(1,1),
       CountryVARCHAR(500),
       ProductVARCHAR(400),
       SalesDECIMAL(16,2),
       CreatedDateDATETIME
)

INSERTINTO#ProductSales
SELECT'INDIA','A',200000,'01/01/2015'
UNIONALL
SELECT'INDIA','B',400000,'02/01/2015'
UNIONALL
SELECT'INDIA','C',100000,'02/01/2015'
UNIONALL
SELECT'USA','A',300000,'03/01/2014'
UNIONALL
SELECT'USA','B',500000,'04/01/2014'
UNIONALL
SELECT'CHINA','A',600000,'03/01/2014'
UNIONALL
SELECT'CHINA','B',800000,'04/01/2014'



Grouping result set using GROUP BY clause in bellow query.


SELECTCountry,Product,SUM(Sales)ASSalesFROM#ProductSales
GROUPBYCountry,Product


Result Set

Country           Product          Sales
------------------------------------------------------
CHINA             A                600000.00
INDIA             A                200000.00
USA               A                300000.00
CHINA             B                800000.00
INDIA             B                400000.00
USA               B                500000.00
INDIA             C                100000.00

(7 row(s) affected)


WITH ROLLUP: It is use to generate a subtotal row and grand total row for aggregate row. Please see following script.


SELECTCountry,Product,SUM(Sales)AS[Total Sales]FROM#ProductSales
GROUPBYCountry,ProductWITHROLLUP


Result Set


Country        Product       Total Sales
------------------------------------------
CHINA          A             600000.00
CHINA          B             800000.00
CHINA          NULL          1400000.00-- Total Sales of China
INDIA          A             200000.00
INDIA          B             400000.00
INDIA          C             100000.00
INDIA          NULL          700000.00-- Total Sales of India
USA            A             300000.00
USA            B             500000.00
USA            NULL          800000.00-- Total Sales of USA
NULL           NULL          2900000.00-- Grand Total sales

(11 row(s) affected)


Viewing all articles
Browse latest Browse all 265

Trending Articles