我有一个 MySQL
数据库,其中有一个名为“orders”的 表
,其中包含我所有的订单。在此表中,我有不同的字段,例如:
id
userId
dateOrder
我只想获取按用户分组的所有订单,这些订单仅适用于执行 2 到 5 个
订单的用户。
但是我的 SQL 查询不起作用。考虑这些条目:
id userId dateOrder
1 138 2013-03-19
2 138 2013-03-19
3 222 2013-03-19
我想要一个 SQL 请求,它只选择至少完成 2 个订单的用户所下的订单。
对于这个例子,SQL 应该返回:
userId 138
我尝试使用 GROUP BY
和 DISTINCT
,但这些都不起作用。你能帮我吗 ?
谢谢!!
最佳答案
您应该能够使用 HAVING
子句来获取结果:
select userid
from orders
group by userid
having COUNT(*) >= 2
and COUNT(*) <= 5
如果您随后想要返回每个订单的所有详细信息,您可以将查询扩展为:
select o1.id, o1.userid, o1.dateorder
from orders o1
where exists (select userid
from orders o2
where o1.userid = o2.userid
group by userid
having COUNT(*) >= 2
and COUNT(*) <= 5)
关于mysql - 统计 SQL 查询结果的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507542/