简体   繁体   中英

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?

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:

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.

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.

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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