【问题标题】:Multiple columns horizontally - Group By month水平多列 - 按月分组
【发布时间】:2021-03-29 00:01:47
【问题描述】:

我有一些返回以下信息的 SQL:

Date Month Balance Transactions
01/01/2020 January 20 Test 1
02/01/2020 January 21 Test 2
01/02/2020 February 20 Test 3
02/02/2020 February 21 Test 4

我想获取信息,所以它是这样的:

Date January Balance Transactions Date February Balance Transactions
01/01/2020 January 20 Test 1 01/02/2020 February 20 Test 3
02/01/2020 January 21 Test 2 02/02/2020 February 21 Test 4

有什么想法吗?我试过 Pivots,它很接近,但不存在。

提前感谢您的帮助!

【问题讨论】:

  • 很接近,但不在那里。 - 请告诉我们它与您的代码有多接近。 Pivot 不应该是close:它是否做某事(基于固定数量和列名的简单要求)。

标签: sql sql-server tsql pivot


【解决方案1】:

如果我理解正确,您可以将条件聚合与row_number() 一起使用:

select max(case when month = 'January' then date end),
       'January',
       max(case when month = 'January' then balance end),
       max(case when month = 'January' then transactions end),
       max(case when month = 'February' then date end),
       'February',
       max(case when month = 'February' then balance end),
       max(case when month = 'February' then transactions end)           
from (select t.*,
             row_number() over (partition by month order by date) as seqnum
      from t
     ) t
group by seqnum
order by seqnum;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2019-01-22
    • 2021-07-07
    • 2017-11-29
    • 1970-01-01
    相关资源
    最近更新 更多