【问题标题】:Retrieving two COUNTs using a single SQL statement使用单个 SQL 语句检索两个 COUNT
【发布时间】:2011-05-06 09:10:41
【问题描述】:

假设 Table1 有 c1 列,其允许值为 1 或 0。

如何通过单个查询检索 0、1 的数量?有可能吗?

对不起,愚蠢的提问方式。

我希望答案在一行,而不是一列。

【问题讨论】:

    标签: sql count group-by


    【解决方案1】:

    这是一个单一的表/索引读取。子查询很可能有两次这样的读取

    SELECT
       COUNT(CASE status WHEN 1 THEN 1 ELSE NULL END) AS Ones,
       COUNT(CASE status WHEN 0 THEN 1 ELSE NULL END) AS Zeros
    FROM
       MyTable
    

    ..它也很便携

    【讨论】:

      【解决方案2】:

      如果我理解正确,只需GROUP BY 那个专栏。

      SELECT c1, count(*)
      FROM Table1
      GROUP BY c1;
      

      【讨论】:

      • 我将投反对票,因为这不会分别计算 1 和 0。:它没有回答问题
      • 这个问题在我提交回复后得到澄清 - 无法改变! :-)
      【解决方案3】:

      另一种方式;

      select
         sum(c1) as ones, 
         count(*) - sum(c1) as zeros
      from
         Table1
      

      【讨论】:

        【解决方案4】:

        取决于您使用的 DBMS。 在 oracle 中,以下是可能的:

        select
         (select count(status) from table1 where status = 0) as status_0,
         (select count(status) from table1 where status = 1) as status_1
        from dual
        

        【讨论】:

          【解决方案5】:

          已经得到答复,但总是(几乎)有不止一种方法可以做到这一点。两个查询的联合?

          select count(*) from t1 where value='0' 
          union
          select count(*) from t1 where value='1' 
          

          【讨论】:

            【解决方案6】:

            从emp中选择uid

            UID 0 0 0 1 1 1 1 0 0

            select distinct
            
            (select count(uid) from emp  where uid = 0) zeros_total,
            
            (select count(uid) from emp where uid = 1) ones_total
            
            from 
            emp
            

            O/P **zeros_total 5 个ones_total 4**

            【讨论】:

              猜你喜欢
              • 2013-05-31
              • 2018-07-09
              • 2020-03-27
              • 2014-01-30
              • 2011-06-13
              • 2012-02-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多