繁体   English   中英

T-SQL - Pivot 为每个组输出不同的 N 行

[英]T-SQL - Pivot out Distinct N rows for each group

我有一张类似于下表的表格,其中包含客户、产品和购买日期。 我正在尝试获取客户列表及其 3 最近购买的 DISTINCT 产品。 我想使用购买日期作为订购结果的一种方式,但我不想看到重复的产品 ID。

顾客 产品 购买日期
1 一个 2020-12-5
2 b 2020-12-5
1 一个 2020-12-4
2 一个 2020-12-3
1 b 2020-12-2
2 b 2020-12-1
1 c 2020-11-30
1 d 2020-11-29
2 b 2020-11-28

理想情况下,我会看到这样的结果

顾客 产品1 产品2 产品3
1 一个 b c
2 b 一个

我尝试过按语句分区和按语句排序,但一切都希望我在最终的 output 中包含日期。 有没有办法做到这一点?

最近的不同产品很棘手。 这需要对每个客户和产品进行一级聚合,然后再进行一级聚合:

select customer,
       max(case when seqnum = 1 then product end) as product_1,
       max(case when seqnum = 2 then product end) as product_2,
       max(case when seqnum = 3 then product end) as product_3
from (select customer, product, max(purchasedate) as max_purchasedate,
             row_number() over (partition by customer order by max(purchasedate) desc) as seqnum
      from t
      group by customer, product
     ) cp
group by customer;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM