如何在SQL Server中正确分组结果

时间:2018-06-21 18:25:28

标签: sql sql-server

对于像这样的表

+----+------+
| Id | Name |
+----+------+    
| 1  | aaa  |
| 1  | bbb  |
| 1  | ccc  |
| 1  | ddd  |
| 1  | eee  |
+----+------+

正确的SELECT语句具有如下输出是什么:

+----+---------------------------------------------------+
| Id |   col1  |   col2   |    col3   |  col4   |  col5  |
+----+---------------------------------------------------+ 
|  1 |   aaa   |   bbb    |    ccc    |   ddd   |   eee  |
+----+---------------------------------------------------+ 

非常感谢!

2 个答案:

答案 0 :(得分:4)

使用row_number()函数:

select Id, max(case when seq = 1 then Name end) as col1,
           max(case when seq = 2 then Name end) as col2,
           max(case when seq = 3 then Name end) as col3,
           max(case when seq = 4 then Name end) as col4,
           max(case when seq = 5 then Name end) as col5
from (select *, row_number() over (partition by Id order by Name) seq
      from table
     ) t
group by Id;

答案 1 :(得分:1)

我将cross applyCASE WHENMAX函数一起使用。

select  x.Id, 
        max(case when v = 'aaa' then Name end) as col1,
        max(case when v = 'bbb' then Name end) as col2,
        max(case when v = 'ccc' then Name end) as col3,
        max(case when v = 'ddd' then Name end) as col4,
        max(case when v = 'eee' then Name end) as col5
from T cross apply(values(Name,id)) x(v,id)
GROUP BY x.Id

sqlfiddle:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=b1b76decac1a931961494fb5c4fe51b7

编辑

感谢@sgeddes指出。

仅使用CASE WHENMAX函数。

select  Id, 
        max(case when Name = 'aaa' then Name end) as col1,
        max(case when Name = 'bbb' then Name end) as col2,
        max(case when Name = 'ccc' then Name end) as col3,
        max(case when Name = 'ddd' then Name end) as col4,
        max(case when Name = 'eee' then Name end) as col5
from T 
GROUP BY Id

sqlfiddle:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=e4f830ca766f240b10412351df56856d