选择购买次数最多的客户,按日期分组
Posted
技术标签:
【中文标题】选择购买次数最多的客户,按日期分组【英文标题】:Selecting the customer who made the most purchases, grouped by date 【发布时间】:2021-08-28 04:05:19 【问题描述】:我有两张桌子
customers
+---------+-------+
| cust_id | name |
+---------+-------+
| 1 | Tom |
+---------+-------+
| 2 | John |
+---------+-------+
| 3 | Lisa |
+---------+-------+
| 4 | Wendy |
+---------+-------+
purchases
+---------------+-------------+---------+
| purchase_date | purchase_id | cust_id |
+---------------+-------------+---------+
| 2021-01-01 | 1 | 1 |
+---------------+-------------+---------+
| 2021-01-01 | 2 | 1 |
+---------------+-------------+---------+
| 2021-01-01 | 3 | 2 |
+---------------+-------------+---------+
| 2021-01-01 | 4 | 1 |
+---------------+-------------+---------+
| 2021-01-01 | 5 | 4 |
+---------------+-------------+---------+
| 2021-01-02 | 6 | 3 |
+---------------+-------------+---------+
| 2021-01-02 | 7 | 3 |
+---------------+-------------+---------+
| 2021-01-02 | 8 | 2 |
+---------------+-------------+---------+
| 2021-01-02 | 9 | 1 |
+---------------+-------------+---------+
| 2021-01-02 | 10 | 4 |
+---------------+-------------+---------+
| 2021-01-03 | 11 | 2 |
+---------------+-------------+---------+
| 2021-01-03 | 12 | 2 |
+---------------+-------------+---------+
| 2021-01-03 | 13 | 3 |
+---------------+-------------+---------+
| 2021-01-03 | 14 | 3 |
+---------------+-------------+---------+
我想按日期查询唯一购买客户的数量(简单)和按日期购买最多的客户的cust_id
。如果多个客户在同一日期进行了相同数量的购买,我想显示较小的cust_id
。结果应如下所示:
+---------------+------------------+-----------------+
| purchase_date | unique_customers | biggest_spender |
+---------------+------------------+-----------------+
| 2021-01-01 | 3 | 1 |
+---------------+------------------+-----------------+
| 2021-01-02 | 4 | 3 |
+---------------+------------------+-----------------+
| 2021-01-03 | 2 | 2 |
+---------------+------------------+-----------------+
【问题讨论】:
【参考方案1】:这是 Postgresql 中的查询,使用mode()
来确定最大支出者,别名为购买表中每个日期的最频繁值
SELECT p.purchase_date, count(DISTINCT p.cust_id) as unique_customers , mode() within group (order by p.cust_id) as biggest_spender
FROM purchases p
GROUP BY p.purchase_date
ORDER BY COUNT(p.cust_id) DESC;
【讨论】:
以上是关于选择购买次数最多的客户,按日期分组的主要内容,如果未能解决你的问题,请参考以下文章