水平多列 - 按月分组
Posted
技术标签:
【中文标题】水平多列 - 按月分组【英文标题】: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:它是否做某事(基于固定数量和列名的简单要求)。 【参考方案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;
【讨论】:
以上是关于水平多列 - 按月分组的主要内容,如果未能解决你的问题,请参考以下文章