【问题标题】:Selecting the amount of users that have no 'thing' assigned to it选择没有分配“事物”的用户数量
【发布时间】:2018-11-03 12:35:37
【问题描述】:

我有一个简化的表格来显示我的问题
名称    动物
比尔       狗
比尔         猫
比尔         鱼
约翰       猫
约翰      鱼
萨拉       狗
萨拉      猫
标记       鱼

我想要没有狗的人数。我试过这个查询。

select count(distinct Name) from Table
where Animal <> 'Dog'



但它返回 4 而不是预期的 2。我做错了什么?

【问题讨论】:

    标签: sql


    【解决方案1】:

    您的查询返回了包含除狗以外的任何动物的名称的计数。

    select distinct name
    from table t1
    where not exists
    (
        select 1 from table t2 where t1.name=t2.name and t2.Animal='Dog'
    )
    

    【讨论】:

      【解决方案2】:

      使用not exists

      select count(distinct t.name) as counts
      from table t
      where not exists (select 1 from table where name = t.name and animal = 'Dog');
      

      对于您当前的查询,您正在根据 animal 名称过滤单个记录,这不会产生所需的结果,因为它应该与 name 列一起。

      【讨论】:

        【解决方案3】:

        您的 where 条件“Animal 'dog'”正在过滤行而不是名称。

        所以试试下面的查询

        Select count(distinct Name) from Table where name not in (
        select Name from Table  where Animal = 'Dog')
        

        【讨论】:

          猜你喜欢
          • 2016-12-18
          • 2021-09-13
          • 2015-07-15
          • 2012-01-17
          • 1970-01-01
          • 1970-01-01
          • 2021-11-16
          • 2017-03-11
          • 2021-10-29
          相关资源
          最近更新 更多