SQL:Max aggregate&按查询分组

时间:2015-02-02 19:43:02

标签: mysql sql psql

我的SQL查询遇到了麻烦。我有以下Orders

 id
 order_number_for_user
 user_id
 date

我想为特定日期的用户选择最近的订单(2015-01-19)。这是一些示例数据

 id| order_number_for_user | user_id |    created      
-------+---------------+---------+---------------
 1 |                     1 |      10 | 2015-01-19
 2 |                     2 |      10 | 2015-01-19
 3 |                     1 |      20 | 2015-01-19
 4 |                     1 |      30 | 2015-01-19
 5 |                     1 |      40 | 2015-01-19
 6 |                     2 |      40 | 2015-02-30

正确的输出是以下行ID 2,3,4,5

这是我构建的破解查询

SELECT id FROM orders WHERE order_number_for_user = 
(SELECT max(order_number_for_user) FROM orders as orders2 
WHERE orders.user_id=orders2.user_id 
AND date(created) = date('2015-01-19'))

此查询选择的行为1,2,3,4,5。不应选择第1行,因为它不是指定日期的用户10的最大订单号。

有人可以告诉我我的查询是如何不正确的吗?

3 个答案:

答案 0 :(得分:0)

你可能想要这个:

SELECT * 
FROM orders
WHERE id IN (
   SELECT MAX(id)
   FROM orders
   WHERE DATE(created) = '2015-01-19'
   GROUP BY user_id
) AS max_order_ids

内部/子查询获取该特定日期每个用户订单的最大ID。然后外部查询获取这些ID的其余订单信息。

您的查询没有进行任何分组,因此MAX()聚合的结果很糟糕。

答案 1 :(得分:0)

使用INNER JOIN

SELECT O1.id
FROM Orders AS O1
INNER JOIN (SELECT user_id, MAX(order_number_for_user) order_number_for_user 
            FROM Orders
            WHERE date(created) = date('2015-01-19')
            GROUP BY user_id) AS O2
    ON O1.user_id = O2.user_id
    AND O1.order_number_for_user = O2.order_number_for_user
WHERE date(O1.created) = date('2015-01-19')

答案 2 :(得分:0)

您需要一个子查询来查找所有user_id及其最大订单,然后您的查询将按以下方式运行:

SELECT id FROM orders, (SELECT user_id,max(order_number_for_user)maxOrderNum FROM orders  GRPOUP BY user_id)作为orders2 orders.user_id = orders2.user_id和orders.order_number_for_user = orders2.maxOrderNum AND orders.date(created)= date('2015-01-19'))