sql server - Combine multiple rows into single row with separate columns in SQL -


i'm having following table structure , expected output listed below how achieve result

id -  date -   score  1  - 2013/04/13 - 100 2  - 2013/04/14 - 92  3  - 2013/04/15 - 33  

expected output :

date -2013-04-13 - 2013-04-14 -  2013-04-15  score -  100      -   92        -    33 

use pivot table operator:

select * (select date, score tablename) t pivot (   max(score)   date in([2013-04-13], [2013-04-14], [2013-04-15]) ) p; 

see in action here:

this give you:

| 2013-04-13 | 2013-04-14 | 2013-04-15 | ---------------------------------------- |        100 |         92 |         33 | 

if want dynamically, have use dynamic sql so. this:

declare @cols nvarchar(max); declare @query nvarchar(max);   select @cols = stuff((select distinct ',' +                         quotename(date)                       tablename                       xml path(''), type                      ).value('.', 'nvarchar(max)')                          , 1, 1, '');  set @query = 'select *               (select date, score tablename) t               pivot               (                 max(score)                 date in( ' + @cols+ ' )               ) p;';   execute(@query); 

see in action here:

note that: assuming have unique dates entries in table, in case max(score) work fine, in case there more dates entries same day can use sum instead. but, have use aggregate function pivot table operator.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -