[英]MYSQL SUM with Inner Select returning max date
我正在嘗試提出一個查詢,該查詢將使用下表(名為sales
):
user_id | order_total | order_date |
1 | 100 | 2012-01-01 |
1 | 200 | 2013-06-04 |
1 | 150 | 2012-01-08 |
2 | 100 | 2015-02-01 |
3 | 105 | 2014-10-27 |
並將返回以下內容:
user_id | order_total | num_orders | last_order |
1 | 450 | 3 | 2013-06-04 |
3 | 105 | 1 | 2014-10-27 |
2 | 100 | 1 | 2015-02-01 |
到目前為止,我想出了以下SQL來獲取結果:
SELECT
DISTINCT a.user_id,
SUM(order_total) AS order_total,
COUNT(*) AS num_orders,
b.order_date as last_order
FROM
`sales` AS a,
(
SELECT
order_date,
user_id
FROM `sales`
ORDER BY order_date DESC
) AS b
WHERE a.user_id = b.user_id
GROUP BY user_id
ORDER BY order_total DESC
但是,問題在於它返回:
user_id | order_total | num_orders | last_order |
1 | 1350 | 9 | 2013-06-04 |
3 | 105 | 1 | 2014-10-27 |
2 | 100 | 1 | 2015-02-01 |
有什么方法可以防止子查詢影響Sum和Count的結果嗎? 還是我走錯路了?
為什么使用子選擇?
SELECT user_id,
SUM(order_total) AS order_total,
MAX(order_date) AS lastOrder,
COUNT(*) AS num_orders
FROM table
GROUP BY user_id
ORDER BY order_total DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.