Tuesday 13 September 2011

PIVOT Table Example In Sqlserver


 A Pivot Table can automatically sort, count, and total the data stored in one table or spreadsheet and create a second table displaying the summarized data. The PIVOT operator turns the values of a specified column into column names, effectively rotating a table.
------------------------------------------


create table Test1 ( [No] int, [ID] int, Date Datetime, Value decimal (38,2))
------------------------------------------
insert into Test1 values (1, 1001, '05/01/2009', 101.00)
insert into Test1 values (1, 1001, '05/15/2009', 102.00)
insert into Test1 values (1, 1001, '05/20/2009', 105.00)
insert into Test1 values (2, 1001, '05/01/2009', 41.00)
insert into Test1 values (2, 1001, '05/15/2009', 44.00)
insert into Test1 values (3, 1001, '06/01/2009', 330.00)
----------------------------------------
select * from Test1
--------------------------------------
SELECT [No] , [ID] ,[05/01/2009] ,[05/15/2009] ,[05/20/2009] ,[06/01/2009]
FROM (
SELECT [No], [ID], [Date], [Value]
FROM Test1) up
PIVOT ( sum([Value]) FOR [Date] in ([05/01/2009] ,[05/15/2009] ,[05/20/2009] ,[06/01/2009]) )AS pvt

No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...