水平多列 - 按月分组
Multiple columns horizontally - Group By month
我有一些SQL其中returns以下信息:
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,它很接近,但不存在。
提前感谢您的帮助!
如果我没理解错的话,你可以结合使用条件聚合 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;
我有一些SQL其中returns以下信息:
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,它很接近,但不存在。
提前感谢您的帮助!
如果我没理解错的话,你可以结合使用条件聚合 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;