gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:33:58 24 4
gpt4 key购买 nike

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

考虑这个表:

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 的某些条件检索(order_id,user_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 的要求)?

最佳答案

您可以为 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'

关于mysql - 基于 GROUP BY 中的单个列使用 DISTINCT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9133068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com