Last active
August 29, 2015 14:22
-
-
Save liuzy163/06bb7ae0650f1efb43ab to your computer and use it in GitHub Desktop.
T-SQL create a simple pivot table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE OrderItem( | |
lineItemId int IDENTITY(1,1) NOT NULL, | |
orderid int NOT NULL, | |
itemName nchar(10) NOT NULL, | |
qty int NOT NULL | |
) | |
GO | |
INSERT INTO OrderItem (orderid,itemName,qty) | |
VALUES (100, 'ipad', 4), | |
( 100, 'iphone', 2), | |
( 100, 'ipod', 10), | |
( 200, 'ipad', 4), | |
( 200, 'iphone', 2), | |
( 300, 'ipod', 10), | |
( 400, 'ipad', 4), | |
( 400, 'iphone', 2), | |
( 500, 'ipod', 10) | |
GO | |
--Show the result in vertical way | |
select itemName, sum(qty) from orderitem group by itemName | |
--This is a home-made "pivot". The next one will be using the pivot function. | |
--Show the result in horizontal way | |
select sum(ipadQty) as ipadQty, sum(iphoneQty) as iphoneQty, sum(ipodQty) ipodQty | |
from | |
( | |
select | |
ipadQty=case when itemName='ipad' then qty else 0 end, | |
iphoneQty=case when itemName='iphone' then qty else 0 end, | |
ipodQty=case when itemName='ipod' then qty else 0 end | |
from | |
(select itemName, sum(qty) as qty from orderitem group by itemName) as vertical | |
) unmerged | |
--Using pivot function to get the total qty for each product | |
select [ipad] as ipadTotalQty, [iphone] as iphoneTotalQty, [ipod] as ipodTotalQty from | |
(select itemname, qty from orderitem ) as sourcetable | |
pivot | |
( | |
sum(qty) for itemname in ([ipad] ,[iphone] ,[ipod]) | |
) as pivotTable | |
--Using pivot function to get the total qty for each order | |
select [100] as order100Qty, [200] as order200Qty, [300] as order300Qty, [400] as order400Qty, [500] as order500Qty from | |
(select orderid, qty from orderitem ) as sourcetable | |
pivot | |
( | |
sum(qty) for orderid in ([100],[200],[300],[400],[500]) | |
) as pivotTable | |
--Using pivot function to get the total qty for each product, grouped by orders | |
select orderid, [ipad] as ipadTotalQty, [iphone] as iphoneTotalQty, [ipod] as ipodTotalQty from | |
(select orderid, itemname, qty from orderitem ) as sourcetable | |
pivot | |
( | |
sum(qty) for itemname in ([ipad],[iphone],[ipod]) | |
) as pivotTable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment