我想转置一个包含用户交易的表格,该表格显示每个用户的购买历史。当前数据集的设计如下:
USER ID | Transaction # | PRODUCT NAME | Amount £
1 1 Free Pass 0.00
1 2 Monthly Pass 10.00
1 3 Monthly Pass 10.00
2 1 Free pass 0.00
2 2 Year Pass 100.00
3 1 Basic pass 5.00
但是,我想转置数据以便每个用户ID显示一行,并水平列出每个事务。我希望得到的SQL的最终结果是:
USER ID | Transaction 1 | Amount 1 | Transaction 2 | Amount 2 | Transaction 3 | Amount 3 |
1 Free Pass 0.00 Monthly Pass 10.00 Monthly Pass 10.00
2 Free Pass 0.00 Year Pass 100.00
3 Basic Pass 5.00
答案 0 :(得分:0)
您可以将conditional aggregation
用作
with tab(USERID, Transaction#, PRODUCTNAME, Amount) as
(
select 1,1,'Free Pass' , 0 union all
select 1,2,'Monthly Pass', 10 union all
select 1,3,'Monthly Pass', 10 union all
select 2,1,'Free pass' , 0 union all
select 2,2,'Year Pass' ,100 union all
select 3,1,'Basic pass' , 5
)
select [USERID],
max(case when Transaction# = 1 then Productname end)
as 'Transaction 1',
max(case when Transaction# = 1 then Amount end)
as 'Amount 1',
max(case when Transaction# = 2 then Productname end)
as 'Transaction 2',
max(case when Transaction# = 2 then Amount end)
as 'Amount 2',
max(case when Transaction# = 3 then Productname end)
as 'Transaction 3',
max(case when Transaction# = 3 then Amount end)
as 'Amount 3'
from tab t
group by [USERID]