MySQL:查找最大订单日

时间:2014-10-20 17:26:46

标签: mysql

我有一个非常基本的订单表:



+----------+---------+------------+---------+
| order_id | cust_id | order_date | book_id |
+----------+---------+------------+---------+
| 1        | 1       | 10/10/2014 | 1       |
+----------+---------+------------+---------+
| 2        | 1       | 10/10/2014 | 2       |
+----------+---------+------------+---------+
| 3        | 1       | 10/12/2014 | 1       |
+----------+---------+------------+---------+
| 4        | 2       | 10/18/2014 | 6       |
+----------+---------+------------+---------+
| 5        | 2       | 10/18/2014 | 77      |
+----------+---------+------------+---------+
| 6        | 2       | 10/18/2014 | 103     |
+----------+---------+------------+---------+
| 7        | 2       | 10/10/2014 | 13      |
+----------+---------+------------+---------+
| 8        | 3       | 10/09/2014 | 1       |
+----------+---------+------------+---------+
| 9        | 3       | 10/11/2014 | 2       |
+----------+---------+------------+---------+
| 10       | 3       | 10/12/2014 | 3       |
+----------+---------+------------+---------+

查询应该:

- 对于每个客户,显示order_date,其中最大订单数量。示例:客户1在10/10/2014有2个订单

- 特殊情况:当客户有大多数订单的多天时,显示最早的日期。示例:客户3在不同日期有3个单项订单。需要显示10/09/2014。

我应该能够在不使用临时表的情况下解决这个问题。

基拉

1 个答案:

答案 0 :(得分:1)

您需要两个条款:1)查找每个客户每天的最大订单数量; 2)找到最大订单数量发生的日期。第二步是消除具有相同订单数量的多天。


SELECT * FROM 
    (SELECT cust_id, 
        order_date, 
        count() cnt 
    FROM 
        orders 
    GROUP BY cust_id, order_date) x 
JOIN 
    (SELECT cust_id, 
            MAX(cnt) max_cnt 
    FROM 
        (SELECT cust_id, 
                order_date, 
                count() AS cnt 
         FROM 
            orders 
        GROUP BY cust_id, order_date) n 
GROUP BY cust_id) y 
ON 
    y.max_cnt = x.cnt 
AND 
    y.cust_id = x.cust_id 

JOIN (SELECT x.cust_id, min(x.order_date) AS dd FROM (SELECT cust_id, order_date, count() cnt FROM orders GROUP BY by cust_id, order_date) x JOIN (SELECT cust_id, MAX(cnt) max_cnt FROM (SELECT cust_id, order_date, count() as cnt FROM orders GROUP BY cust_id, order_date) n GROUP BY cust_id) y ON y.max_cnt = x.cnt AND y.cust_id = x.cust_id GROUP BY cust_id) AS t2 ON t2.cust_id=x.cust_id AND t2.dd=x.order_date;