SQL根据组提供新列

时间:2017-07-06 00:15:20

标签: sql sql-server tsql

我有下表:

ID | Group |  Miles
1  |    1  |   23
2  |    1  |   38
3  |    1  |   42
1  |    2  |   33
2  |    2  |   42
1  |    3  |   35
2  |    3  |   43
3  |    3  |   47

想得到

id  miles1  miles2   miles3 
1 | 23     | 33    | 35
2 | 38     | 42    | 43
3 | 42     | Null  | 47

由于

2 个答案:

答案 0 :(得分:4)

另一种选择是PIVOT

示例

Select [ID]
      ,Miles1 = [1]
      ,Miles2 = [2]
      ,Miles3 = [3]
 From YourTable
 Pivot (sum([Miles]) For [Group] in ([1],[2],[3]) ) p

<强>返回

ID  Miles1  Miles2  Miles3
1   23      33      35
2   38      42      43
3   42      NULL    47

答案 1 :(得分:3)

select id, 
       sum(case when group = 1 then miles end) as miles1,
       sum(case when group = 2 then miles end) as miles2,
       sum(case when group = 3 then miles end) as miles3
from your_table
group by id