Thursday, January 5, 2017

SQL Server -Pivoting the Data

-- Suppress data loading messages
SET NOCOUNT ON

-- Create Sample Data using a Table Varable
create table OrderDetail
(orderid int,
 productname varchar(30),
 productqty int)

-- Load Sample Data
INSERT INTO OrderDetail VALUES (1, 'Gift Card', 2)
INSERT INTO OrderDetail VALUES (1, 'Shipping', 1)
INSERT INTO OrderDetail VALUES (2, 'Gift Card', 2)
INSERT INTO OrderDetail VALUES (2, 'T-Shirt', 2)
INSERT INTO OrderDetail VALUES (2, 'Shipping', 2)
go
--Query to Retrieve Desired Data
SELECT orderid, [Gift Card], [T-Shirt], [Shipping]
FROM
(
SELECT orderid, productname, productqty
FROM OrderDetail) AS source
PIVOT
(
SUM(ProductQty)
FOR ProductName IN ([Gift Card], [T-Shirt], [Shipping])
) as pvt

go
select * from OrderDetail
go
select orderid,[gift card],[T-Shirt],[shipping] from
(select orderID,Productname,productqty from OrderDetail) as source
pivot
(sum(productqty) for productname in ([gift card],[T-Shirt],[shipping])
)as pvt
go
SELECT OrderID,
SUM( ( CASE WHEN productname = 'Gift Card' THEN productqty ELSE 0 END ) ) AS [Gift Cards],
SUM( ( CASE WHEN productname = 'T-Shirt' THEN productqty ELSE 0 END ) ) AS [T-Shirt],
SUM( ( CASE WHEN productname = 'Shipping' THEN productqty ELSE 0 END ) ) AS [Shipping]
FROM OrderDetail
GROUP BY OrderID

No comments:

Search This Blog

DAX - Grouping on multiple columns and the count

Please go thorugh the below URL for entire soultion. http://community.powerbi.com/t5/Desktop/DAX-Grouping-on-multiple-columns-and-the-cou...