【问题标题】:Sql subquery comparing two counts比较两个计数的 Sql 子查询
【发布时间】:2018-03-01 18:31:04
【问题描述】:

我有以下查询,它返回登记册中所有类型为“C”的人以及每个人为“C”类型的行数。每个人都可以有'C'型或'V'型

select count(type), number_document 
from register 
where type = 'C' 
group by number_document ;

我只想返回他的所有行都具有“C”类型的人,所以我需要做一个子查询,将总行数与计数(类型)进行比较。

我不知道如何在这里引入子查询。

【问题讨论】:

  • 请标记您的 DBMS(包括版本)

标签: sql count subquery


【解决方案1】:

您可以使用 NOT EXISTS 来排除也具有“V”类型的用户:

select count(type), number_document 
from register ro 
where type = 'C' 
    AND NOT EXISTS 
   (SELECT TOP 1 NULL 
    FROM register ri 
    WHERE ri.User = ro.User 
        AND ri.type='V')
group by number_document;

【讨论】:

    【解决方案2】:

    这对你有用吗?

    select count(r.type), r.number_document 
    from register r
    where r.type = 'C' AND NOT EXISTS (
        SELECT *
        FROM register r2
        WHERE r.number_document = r2.number_document AND r2.type <> 'C'
    )
    group by r.number_document ;
    

    【讨论】:

      【解决方案3】:

      以下查询有两个条件

      1. 过滤所有 'type' 值都相同的寄存器
      2. 然后过滤'C'类型的人

        select count(r.type), r.number_document 
        from register r
        where r.type = ALL (
            SELECT r2.type
            FROM register r2
            WHERE r.number_document = r2.number_document
        )
        AND r.type = 'C'
        group by r.number_document ;
        

      【讨论】:

        【解决方案4】:

        这个怎么样? HAVING 子句检查唯一的 TYPE 列值是否为 'C'(因为 MIN = MAX = C)。

        select number_document, count(*)
        from register
        group by number_document
        having min(type) = max(type) and min(type) = 'C';
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-04
          • 2010-11-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-01
          • 2014-01-07
          相关资源
          最近更新 更多