0

试图弄清楚如何编写一个透视 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) 时,它只返回最大值,我想显示所有日期。

4

1 回答 1

1

正如我在评论中提到的,你不能PIVOT/Cross Tag没有聚合,因为它是一种聚合形式。但是,就我个人而言,我建议使用后者(也称为条件聚合),因为它的限制要少得多。然后您可以执行以下操作:

SELECT ID,
       Product,
       MAX(CASE Event WHEN 'Search' THEN Date END) AS Search,
       MAX(CASE Event WHEN 'Product Page' THEN Date END) AS ProductPage,
       MAX(CASE Event WHEN 'BOught' THEN Date END) AS Bough
FROM (VALUES(1,'Laptop','Search      ','2020-07-17T14:41:13.535'),
            (1,'Laptop','Product Page','2020-07-17T14:41:13.535'),
            (1,'Laptop','Bought      ','2020-07-17T14:41:13.535'),
            (1,'Tablet','Search      ','2020-07-18T14:41:13.535'),
            (1,'Tablet','Product Page','2020-07-18T14:41:13.535'),
            (1,'Tablet','Bought      ','2020-07-18T14:41:13.535'))V(ID,Product,Event,Date)
GROUP BY ID,
         Product;
于 2021-02-12T14:31:15.160 回答