SQL,需要从多行中取出一些数据放到一行中

SQL, need to take some data from multiple rows and put into one row

我有一个 table 包含以下信息

id  user_id x   y   v
2784    26  1   1   10
2784    26  1   2   21
2784    26  1   3   4
2784    26  1   4   5
2784    26  1   5   33
2784    26  2   1   13
2784    26  2   2   9
2784    26  2   3   18
2784    26  2   4   35
2784    26  2   5   8
2784    26  3   1   12
2784    26  3   2   7
2784    26  3   3   2
2784    26  3   4   22
2784    26  3   5   1

我希望能够 运行 一些 MSsql 代码为每个 x 值创建一行

      y  v   y  v  y  v  y  v  y  v 
2784  1  10  2  21 3  4  4  5  5  33
2784  1  13  2  9  3  18 4  35 5  8 

这可能吗?谢谢

您可以使用 GROUP BYCASE 来完成,例如像这样:

select id
     , max(case when y = 1 then y end) as y
     , sum(case when y = 1 then v end) as v
     , max(case when y = 2 then y end) as y
     , sum(case when y = 2 then v end) as v
     , max(case when y = 3 then y end) as y
     , sum(case when y = 3 then v end) as v
     , max(case when y = 4 then y end) as y
     , sum(case when y = 4 then v end) as v
     , max(case when y = 5 then y end) as y
     , sum(case when y = 5 then v end) as v
  from data
 group by id, x;

输出

id      y   v   y   v   y   v   y   v   y   v
2784    1   10  2   21  3   4   4   5   5   33
2784    1   13  2   9   3   18  4   35  5   8
2784    1   12  2   7   3   2   4   22  5   1

有关演示,请参阅 SQL Fiddle