我正在尝试获取状态大于1的所有行。
我的桌子:
user_id|state
--------------
1000000|Active
1000000|Created
1000001|Active
1000000|Deleted
1000002|Active
1000001|Created
1000003|Active
我的查询:
select user_id, count(state) from docs group by user_id order by count(state) desc;
结果是:
user_id | count(state)
1000000 | 3
1000001 | 2
1000002 | 1
1000003 | 1
但是我只需要打印count(state)大于1的值
我正在尝试此操作,但是它不起作用:
select user_id, count(state) from docs where count(state) > 1 group by user_id;
答案 0 :(得分:3)
当应用GROUP BY时,HAVING可以为您过滤不必要的行。根据您的目的尝试以下查询。 WHERE子句用于过滤行,它适用于每一行,而HAVING子句用于过滤SQL中的组
SELECT user_id,
COUNT(state)
FROM docs
GROUP BY user_id
HAVING COUNT(state) > 1
ORDER BY COUNT(state) DESC;
答案 1 :(得分:2)
您可能需要使用“具有”子句。
select user_id, count(state)
from docs
group by user_id
having count(state) > 1
order by count(state) desc;
答案 2 :(得分:0)
按您的代码行事;
select user_id, count(state) from docs group by user_id order by count(state) desc;
it will be easy and simple to modify.
尝试一下:
select user_id, count(state) from docs group by user_id where count(state) > 1 order by count(state) desc;
这应该工作正常。您的反馈意见将帮助我进一步进行更多研究。祝你好运!
答案 3 :(得分:0)
您还可以使用子查询的概念。您可以阅读有关子查询here的更多信息。
在下面的查询中,内部查询将获取状态及其对应的user_id的计数,而外部查询将过滤这些结果以显示计数> = 1的结果。
SELECT * FROM (select user_id, count(state) as count from docs group by user_id) WHERE count>1 order by count desc;
答案 4 :(得分:0)
从文档中选择user_id,state,其中state = (从(选择状态,计数(状态)'计数'从(按状态具有count(状态)!= 1的状态从文档组中选择状态)选择为状态),其中temp.state = Docs.state)
答案 5 :(得分:-2)
select *
from (select user_id, count(state) as [count]
from docs
group by user_id)
where count > 1
order by count(state) desc;
应该做到这一点