使用基于GROUP BY中单个列的DISTINCT

时间:2012-02-03 17:46:32

标签: mysql

这个问题往往会出现很多,但我还没有找到对我有意义或适用的答案。

考虑下表:

order_id   user_id   order_date
1           1        2012-01-01
1           1        2012-01-15
2           2        2012-01-15
2           2        2012-01-20
2           2        2012-01-25
3           2        2012-01-15
3           2        2012-01-16
4           2        2012-01-15
4           2        2012-01-16

我想基于order_date上的某些条件检索user_id不同的(order_id,user_id)。

到目前为止,我有这个问题:

SELECT user_id, order_id, MAX(order_date) FROM orders
GROUP BY order_id
HAVING
MAX(order_date) < '2012-01-20'

返回

user_id   order_id   MAX(order_date)
1          1         2012-01-15
2          3         2012-01-16
2          4         2012-01-16

但是,我希望此结果集也基于最大order_id分组在user_id上。我想要:

user_id   order_id   MAX(order_date)
1          1         2012-01-15
2          4         2012-01-16

如何基于order_id进行GROUP BY,然后在user_id上进行分组(或者可能不同,如果我放弃了MAX order_id的要求)?

3 个答案:

答案 0 :(得分:0)

您可以为GROUP BY指定多个列,请尝试以下操作:

SELECT user_id, order_id, MAX(order_date) FROM orders
GROUP BY order_id, user_id
HAVING
MAX(order_date) < '2012-01-20'

答案 1 :(得分:0)

SELECT o.order_id, MAX(o.user_id) AS MaxUserId, q.MaxOrderDate
    FROM orders o
        INNER JOIN (SELECT order_id, MAX(order_date) AS MaxOrderDate
                        FROM orders
                        GROUP BY order_id
                        HAVING MAX(order_date) < '2012-01-20') q
            ON o.order_id= q.order_id
                AND o.order_date = q.MaxOrderDate
   GROUP BY o.order_id, q.MaxOrderDate

答案 2 :(得分:0)

怎么样?

SELECT S1.user_id, S1.order_id, S1.maxDate from
    (SELECT o1.user_id, o1.order_id, MAX(o1.order_date) maxDate FROM o1
    GROUP BY o1.order_id
    HAVING MAX(o1.order_date) < '2012-01-20') S1
LEFT JOIN o2 ON (S1.user_id = o2.user_id AND S1.order_id < o2.order_id)
WHERE (o2.order_id IS null)

注意:o1o2都是订单表

这应该按预期工作,否则我可能误解了要求。这是example