内部选择的MYSQL SUM返回最大日期

时间:2015-02-28 10:59:49

标签: mysql sql

我正在尝试提出一个查询,该查询将采用下表(名为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的结果?或者我是以错误的方式解决这个问题?

1 个答案:

答案 0 :(得分:5)

你为什么要使用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