March 8, 2010 at 6:13 am
This is the script.
– Create Table
create table T1 ( [No] int, [ID] int, Date Datetime, Value decimal (38,2))
– Insert data into the table
insert into T1 values (1, 1001, ‘05/01/2009′, 101.00)
insert into T1 values (1, 1001, ‘05/15/2009′, 102.00)
insert into T1 values (1, 1001, ‘05/20/2009′, 105.00)
insert into T1 values (2, 1001, ‘05/01/2009′, 41.00)
insert into T1 values (2, 1001, ‘05/15/2009′, 44.00)
insert into T1 values (3, 1001, ‘06/01/2009′, 330.00)
– Check the Data
select * from T1
– Using Pivot key word to get required output
SELECT [No] , [ID] ,[05/01/2009] ,[05/15/2009] ,[05/20/2009] ,[06/01/2009]
FROM (
SELECT [No], [ID], [Date], [Value]
FROM T1) up
PIVOT ( sum([Value]) FOR [Date] in ([05/01/2009] ,[05/15/2009] ,[05/20/2009] ,[06/01/2009]) )AS pvt
Is it possible to use two aggreation in the PIVOT? If possible, can you please suggestion how to use it?
Another thing that if i have around 100 of Dates and i want to use pivot query for this to find out the avg Value Datewise. so what to to for this ?
e.g
March 8, 2010 at 7:26 am
The answers are in two excellent articles on this site by MVP Jeff Moden:
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns[/url]
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs[/url]
Part 1 covers your first question.
Part 2 covers the second.
Neat.
edit: typo
Paul White
SQLPerformance.com
SQLkiwi blog
@SQL_Kiwi
March 8, 2010 at 7:29 pm
Thanks for the referral, Paul.
--Jeff Moden
Change is inevitable... Change for the better is not.
March 8, 2010 at 9:46 pm
Jeff Moden (3/8/2010)
Thanks for the referral, Paul.
No worries 🙂
Paul White
SQLPerformance.com
SQLkiwi blog
@SQL_Kiwi
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply