我无法提出查询来获取客户 ID 列表及其第 20 次购买的日期。
我得到了一个名为 transactions 的表,其中列名为 customer_id 和purchase_date。表中的每一行都等于一笔交易。
| customer_id | 购买日期 |
|---|---|
| 1 | 2020-11-19 |
| 2 | 2022-01-01 |
| 3 | 2021-12-05 |
| 3 | 2021-12-09 |
| 3 | 2021-12-16 |
我尝试这样做,并假设我必须计算 customer_id 被提及的次数,如果计数等于 20,则返回 id 编号。
SELECT customer_id, MAX(purchase_date)
FROM transactions
(
SELECT customer_id,
FROM transactions
GROUP BY customer_id
HAVING COUNT (customer_id) =20
)
如何让它返回 customer_id 列表以及第 20 次交易的日期?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您需要选择属于customer_id的交易行,并按第20行过滤结果
SELECT * FROM ( SELECT customer_id, purchase_date, ROW_NUMBER() OVER( PARTITION BY customer_id ORDER BY purchase_date DESC ) AS nth FROM transactions ) as t WHERE nth = 20