按列分组数据

时间:2011-12-19 17:35:19

标签: sql sql-server sql-server-2008 tsql

  

可能重复:
  dynamic sql pivot in sql server

我有一个名为Col_values的表,Col_ID是数据的标识字段:

Val_ID       Col_ID       Value
76951792     3            Closed
76951791     3            Closed
76951790     25           Open
76951789     25           Closed
76951792     1            US
76951791     1            Canada

和另一个名为Et_Col的表,数据如下:

Col_ID   Col_Name   D_ID
3        Status     1
25       Status     2
1        Country    1

我希望输出为:

Val_ID       Status    Country
76951792    Closed     US
76951791    Closed     Canada
76951790    Open       Null
76951789    Closed     Null

所以我写了一个游标来获取输出,游标返回如下语句:

  Select val_ID
    ,max(case when Col_ID = 3 then Value end) as Status
    ,max(case when Col_ID = 25 then Value end) as Status
   ,max(CASE WHEN Col_ID = 1 THEN VALUE END ) AS Country
    From Col_values
    Group by Val_ID

这给了我输出:

Val_ID    Status    Status    Country
76951792  Closed    Null      US
76951791  Closed    Null      Canada
76951789  Null      Closed    Null
76951790  Null      Open      Null

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

select val_id, value as Status
from col_values

这将产生您想要的输出。为什么你认为你需要对数据进行分组才能实现?

答案 1 :(得分:1)

应该可以更改光标,以便它生成如下的sql:

select 
    val_id
    ,max(case when Col_name = 'Status' then Value end) as Status
    ,max(case when Col_name = 'Country' then Value end) as Country
from
    col_values v
    join ET_Col c on v.col_id=c.col_id

group by val_id

不同之处在于您使用col_name在列之间进行拆分而不是col_id,因此加倍的列名将合并。