如何将“值列”设置为值行?

时间:2018-07-05 05:05:50

标签: sql sql-server pivot-table

我有一个表dbo.tbbuy,如下所示:

我想获取如下结果表:

enter image description here

1 个答案:

答案 0 :(得分:0)

SQL表表示无序集。您的表没有顺序,因此您可以只使用min()max()

select name, min(value) as value1, max(value) as value2
from t
group by name;

更通用的方法使用条件聚合:

select name,
       max(case when seqnum = 1 then value end) as value_1,
       max(case when seqnum = 2 then value end) as value_2,
       max(case when seqnum = 3 then value end) as value_3
from (select t.*,
             row_number() over (partition by name order by name) as seqnum
      from t
     ) t
group by name;

如果要按特定顺序排列值,请更改order by子句。