试图弄清楚如何编写一个透视 sql server 语句。我有下表
源表
ID |Product |Event |Date
-----------------------------------------------
1 |Laptop |Search |2020-07-17 14:41:13.535
1 |Laptop |Product Page |2020-07-17 14:41:13.535
1 |Laptop |Bought |2020-07-17 14:41:13.535
1 |Tablet |Search |2020-07-18 14:41:13.535
1 |Tablet |Product Page |2020-07-18 14:41:13.535
1 |Tablet |Bought |2020-07-18 14:41:13.535
期望的输出
ID| Product |Search |Product Page |Bought
-----------------------------------------------------------------------------------------------
1 | Laptop |2020-07-17 14:41:13.535 |2020-07-17 14:41:13.535 |2020-07-17 14:41:13.535
1 | Tablet |2020-07-18 14:41:13.535 |2020-07-18 14:41:13.535 |2020-07-18 14:41:13.535
我的查询看起来像
with V1 as
(
select id,product,event,start_time_local
from table1
)
select id,product,
[search],[product page],[Bought] from V1
PIVOT (Max(start_time_local) for event_type in ([search],[product page],[Bought]))
as PivotTable;
当我取 Max(date) 时,它只返回最大值,我想显示所有日期。