SQL查询和故障排除

时间:2019-06-15 02:44:28

标签: sql sql-server-2012

大家好,我有一个有关重新排列数据的sql查询的问题。 查询结果看起来像这样。

Area | Name | Amount |   Date
  1  |  N1  |   10   | 6/15/2019
  2  |  N1  |   20   | 6/15/2019
  3  |  N1  |   30   | 6/15/2019
  4  |  N1  |   77   | 6/15/2019
  1  |  N2  |   30   | 6/15/2019
  2  |  N2  |   45   | 6/15/2019
  3  |  N2  |   60   | 6/15/2019

是否可以将查询结果变成类似的内容,以及如何实现?

Area | Name | Amount | Name | Amount
  1  |  N1  |   10   |  N2  |   30
  2  |  N1  |   20   |  N2  |   45
  3  |  N1  |   30   |  N2  |   60
  4  |  N1  |   77   | Null |  Null

问题是用户不知道名称,因为它是生成的 取决于插入日期。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么条件聚合将起作用:

select area,
       max(case when seqnum = 1 then name end) as name1,
       max(case when seqnum = 1 then amount end) as amount1,
       max(case when seqnum = 2 then name end) as name2,
       max(case when seqnum = 2 then amount end) as amount2
from (select t.*,
             row_number() over (partition by area order by name) as seqnum
      from t
     ) t
group by area;