使用多列分组的单个结果集

时间:2017-08-10 14:26:34

标签: sql tsql

我正在使用以下数据

 Name  | Number | Stage
 Bob   | 101    |  1
 James | 102    |  2
 Chris | 57     |  5
 James | 3      |  1
 James | 76     |  1
 Bob   | 95     |  2
 Bob   | 18     |  2
 Bob   | 7      |  3
 Bob   | 11     |  5
 Bob   | 1      |  4

我希望能够将结果输出为与此类似的格式

Name  | Stage1 | Stage2 | Stage3 | Stage4 | Stage5
Bob   |  1     |  2     | 1      | 1      | 1
Chris |  0     |  0     | 0      | 0      | 5
James |  2     |  1     | 0      | 0      | 0

我知道我可以根据名称使用以下

分组的每个阶段获得计数
select distinct name, count(stage) [Stage1]
from table
where stage = 1
group by name

但我很遗憾如何将它组合成一个按名称分组的结果集

2 个答案:

答案 0 :(得分:3)

这可能是,你在找什么:

SELECT Name
      ,SUM(IIF(Stage=1,1,0)) AS Stage1
      ,SUM(IIF(Stage=2,1,0)) AS Stage2
      ,SUM(IIF(Stage=3,1,0)) AS Stage3
      ,SUM(IIF(Stage=4,1,0)) AS Stage4
      ,SUM(IIF(Stage=5,1,0)) AS Stage5
  FROM mytable
 GROUP BY Name

答案 1 :(得分:0)

如果您希望pivoting使用pivot:

select 
    [Name],
    isnull([1], 0) Stage1,
    isnull([2], 0) Stage2, 
    isnull([3], 0) Stage3, 
    isnull([4], 0) Stage4, 
    isnull([5], 0) Stage5
from table
pivot (count(Number) for Stage in ([1], [2], [3], [4], [5])) p