【问题标题】:GROUP BY and WHERE clause in one query一个查询中的 GROUP BY 和 WHERE 子句
【发布时间】:2019-06-11 08:52:04
【问题描述】:

我正在尝试获取状态大于 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;

我的例子: http://www.sqlfiddle.com/#!9/b2716b/2

【问题讨论】:

  • WHERE限制SELECT显示的行数,HAVING限制GROUP BY显示的组数,所以需要have而不是where

标签: sql group-by where-clause


【解决方案1】:

当应用了 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;

【讨论】:

    【解决方案2】:

    您可能需要使用“有”子句。

    select user_id, count(state) 
    from docs 
    group by user_id 
    having count(state) > 1
    order by count(state) desc;
    

    【讨论】:

      【解决方案3】:

      按照您的代码执行;

      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;
      

      这应该可以正常工作。您的反馈将帮助我进一步进行更多研究。祝你好运!!!

      【讨论】:

      • 聚合函数条件需要一个 HAVING 子句,而不是 WHERE 子句。
      【解决方案4】:

      您也可以使用子查询的概念。你可以阅读更多关于子查询here的内容。

      在下面的查询中,内部查询将获取状态计数及其对应的 user_id,而外部查询将过滤这些结果以显示 count >=1 的结果。

       SELECT * FROM (select user_id, count(state) as count from docs group by user_id) WHERE count>1 order by count desc;
      

      【讨论】:

        【解决方案5】:

        从 state = 的文档中选择 user_id,state (select state from(select state,count(state) 'count' from docs group by state with count(state)!=1) as temp where temp.state=Docs.state)

        【讨论】:

          【解决方案6】:
          select *
          from (select user_id, count(state) as [count] 
                from docs
                group by user_id)
          where count > 1
          order by count(state) desc;
          

          应该做的伎俩

          【讨论】:

          • 将 ORDER BY 从子查询中移出。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-02
          • 1970-01-01
          • 2022-12-14
          • 1970-01-01
          • 1970-01-01
          • 2015-10-23
          相关资源
          最近更新 更多