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.
| Author |
Topic |
|
n3xus
Starting Member
6 Posts |
Posted - 2011-04-08 : 01:39:54
|
This is my tableEMP_ID [DATE] Attendance106205 2011-02-01 A106206 2011-02-01 S106207 2011-02-01 A106205 2011-02-02 A106206 2011-02-02 A106207 2011-02-02 A I'm trying query it like this. Is it possible to do it in SQL Server? 2011-02-01 2011-02-01106205 A A106206 S A106207 A A |
|
|
nathans
Aged Yak Warrior
938 Posts |
Posted - 2011-04-08 : 02:11:00
|
| If you want the columns to be added dynamically please search on this site for dynamic pivot/crosstab article. To use static column list:-- using caseselect EMP_ID, max(case when [DATE] = '2011-02-01' then Attendance else null end) [2011-02-01], max(case when [DATE] = '2011-02-02' then Attendance else null end) [2011-02-02]from @tgroupby EMP_IDselect EMP_ID, [2011-02-01], [2011-02-02]from @t p pivot (max(Attendance) for [DATE] IN ([2011-02-01],[2011-02-02])) as pvtNathan Skerl |
 |
|
|
McDebil
Starting Member
23 Posts |
Posted - 2011-04-08 : 03:10:56
|
| Change the table name 'StuffTest' to your table name.DECLARE @sqlString AS NVARCHAR(MAX)SET @sqlString = 'SELECT EMP_ID,' + STUFF((SELECT DISTINCT (',[' + [DATE] + ']') FROM StuffTest FOR XML PATH('')),1,1, '') +'FROM StuffTest p' + CHAR(13) +'PIVOT (MAX(Attendance) FOR [DATE] IN (' + STUFF((SELECT DISTINCT (',[' + [DATE] + ']') FROM StuffTest FOR XML PATH('')),1,1, '') +')) as pvt'EXECUTE (@sqlString)McDebil |
 |
|
|
n3xus
Starting Member
6 Posts |
Posted - 2011-04-12 : 03:05:32
|
| thank you so much guys. :) |
 |
|
|
|
|
|
|
|