简体   繁体   English

如何计算sql中零的数量?

[英]How do I count the number of zeros in sql?

I have a column that has a value that is either 0 or 1. how do i count the numbers of zeros?我有一列的值为 0 或 1。我如何计算零的数量?

SELECT A.id
FROM table1 A
GROUP BY A.id
HAVING SUM(A.zeroorone) >=
ALL (SELECT SUM(AA.zeroorone)
    FROM table1 AA
    GROUP BY AA.id)

I know this counts the number of ones.我知道这计算的数量。 I cant seem to get it我似乎无法得到它

A CASE statement would do nicely: CASE 语句会做得很好:

SELECT SUM(CASE WHEN zeroorone = 0 
                THEN 1 
                ELSE 0 END) AS TOTAL_ZEROS
  FROM table1 

Using count...使用计数...

SELECT COUNT(*) FROM table1 
WHERE zeroone=0

If you just want the count of zeroes in the table, then use this:如果您只想要表中零的计数,请使用以下命令:

SELECT COUNT(1) AS COUNT_OF_ZEROES
FROM table1
WHERE zeroone = 0

If you want a count per id, then use this.如果您想要每个 id 的计数,请使用它。

SELECT id, COUNT(1) AS COUNT_OF_ZEROES
FROM table1
WHERE zeroone = 0
GROUP BY id

i know this counts the number of ones我知道这很重要

Are you sure?你确定吗? It rather seems to me it returns id s where its tally of ones is greater or equal to its tally of zeros.在我看来,它返回id s,其中它的计数大于或等于它的零计数。

If you are happy that the query does what you want but you want to reverse the effect -- eg return id s where its tally of zeros is greater or equal to its tally of ones -- then just change the comparison operator:如果您对查询执行您想要的操作感到高兴,但您想要反转效果——例如返回id s,其中它的零计数大于或等于它的计数——那么只需更改比较运算符:

SELECT A.id
FROM table1 A
GROUP BY A.id
HAVING SUM(A.zeroorone) <=  -- changed from >=
ALL (SELECT SUM(AA.zeroorone)
    FROM table1 AA
    GROUP BY AA.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM