[英]MYSQL SUM with Inner Select returning max date
I am trying to come up with a single query which will take the following table (named sales
): 我正在尝试提出一个查询,该查询将使用下表(名为
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 |
And will return the following: 并将返回以下内容:
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 |
So far I have come up with the following SQL to get the result: 到目前为止,我想出了以下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
The problem, however is that it returns: 但是,问题在于它返回:
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 |
Is there some way to prevent the sub-query from affecting the results of Sum and Count? 有什么方法可以防止子查询影响Sum和Count的结果吗? Or am I going about this the wrong way?
还是我走错路了?
why are you using a subselect? 为什么使用子选择?
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.