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
 General SQL Server Forums
 New to SQL Server Programming
 NEED TRICKY SELECT STATEMENT

Author  Topic 

jazzyb
Starting Member

20 Posts

Posted - 2011-03-22 : 09:20:23
I have table named as "paytable" with following structure and data


empid , month , salary
1 , January , 1000
2 , January , 1000
3 , January , 1000
.
.
.
1 , February , 1500
2 , February , 1500
3 , February , 2000
.
.
.
1 , March , 2000
2 , March , 2000
3 , March 2500
.
.
.


What SELECT QUERY should I use to get the output in following format:

empid , January_Salary , February_Salary , March_Salary
1 , 1000 , 1500 , 2000
2 , 1000 , 1500 , 2000
3 , 1000 , 2000 , 2500
.
.
.

Thanks

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2011-03-22 : 09:22:14
if you are using SQL 2005 / 2008, check out PIVOT operator
http://msdn.microsoft.com/en-us/library/ms177410.aspx


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-03-22 : 10:12:56
Also refer
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

jonassi
Starting Member

2 Posts

Posted - 2011-03-22 : 11:45:26
You can also use CASE.

SELECT
empid
,CASE WHEN month ='January' THEN salary END AS [January_salary]
,CASE WHEN month ='February' THEN salary END AS [February_salary]
...
FROM paytable
Go to Top of Page

jazzyb
Starting Member

20 Posts

Posted - 2011-03-22 : 12:24:11
Respected Friends,

Thanks for replies!

I am using MS Sql Express 2005

But my problem is not solved. Pivot seems to be very difficult when I used this gives syntax error. I tried may different syntax by searching form google.

Secondaly Select Case is also problem it gives null for one column when showing data for other column.

May you suggest correct syntax Pivot query for my table. I am irritated by searching solution from internet.

Thanks
Go to Top of Page

jonassi
Starting Member

2 Posts

Posted - 2011-03-22 : 12:52:23
You need to group on empid, try this.


SELECT
empid
,SUM(CASE WHEN month ='January' THEN salary END) AS [January_salary]
,SUM(CASE WHEN month ='February' THEN salary END) AS [February_salary]
...
FROM paytable
GROUP BY emp_id
Go to Top of Page
   

- Advertisement -