Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Help needed in SQL Query

Author  Topic 

sql_2k
Starting Member

26 Posts

Posted - 2008-06-05 : 01:25:05
Hi all,

I have a query which returns below result.

PID PName Quarter Value
1 NewLook Q1 1000
1 NewLook Q2 4200
1 NewLook Q3 5400
1 NewLook Q4 9000
2 Pepe Q1 3000
2 Pepe Q2 1200
2 Pepe Q3 4400

What I want - Another query on the above result which will return me the data as below without using temporary tables

PID Pname Q1 Q2 Q3 Q4
1 NewLook 1000 4200 5400 9000
1 Pepe 3000 1200 4400 0


Please advise.

Vinnie881
Master Smack Fu Yak Hacker

1231 Posts

Posted - 2008-06-05 : 01:31:15
Just a fairly simple pivot table query. Here is how to use a pivot query.

http://www.mssqltips.com/tip.asp?tip=1019
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-06-05 : 01:45:44
or use GROUP BY to achieve this:-
SELECT PID,PName,
SUM(CASE WHEN Quarter = 'Q1' THEN Value ELSE 0 END) AS Q1,
SUM(CASE WHEN Quarter = 'Q2' THEN Value ELSE 0 END) AS Q2,
SUM(CASE WHEN Quarter = 'Q3' THEN Value ELSE 0 END) AS Q3,
SUM(CASE WHEN Quarter = 'Q4' THEN Value ELSE 0 END) AS Q4
FROM Table
GROUP BY PID,PName
Go to Top of Page
   

- Advertisement -