How to count the rows which contains non zero values in sql

最后都变了- 提交于 2021-02-17 05:09:16

问题


SELECT round(COUNT(dmd_1wk),2) AS NBR_ITEMS_1WK
  FROM table;

Field dmd_1wk has so many zeros in it. How do I Count the non zero values?


回答1:


Methinks bluefeets answer is probably what you are really looking for, as it sounds like you just want to count non-zeros; but this will get you a count of zero and non-zero items if that's not the case:

SELECT 
  ROUND(SUM(CASE NVL(dmd_1wk, 0) = 0 THEN 1 ELSE 0 END), 2) AS "Zeros",
  ROUND(SUM(CASE NVL(dmd_1wk, 0) != 0 THEN 1 ELSE 0 END), 2) AS "NonZeros"
FROM table

Although there is no point in rounding a whole number, I've included your original ROUNDs as I'm guessing you're using it for formatting, but you might want to use:

TO_CHAR(SUM(...), '999.00')

as that's the intended function for formatting numbers.




回答2:


It sounds like you just need to add a WHERE clause:

SELECT 
      round(COUNT(dmd_1wk),2) AS NBR_ITEMS_1WK
FROM table
WHERE dmd_1wk <> 0;

If you want the count of both non-zero and zero values, then you can use something like:

SELECT 
   round(COUNT(case when dmd_1wk <> 0 then dmd_1wk end),2) AS NBR_ITEMS_1WK_NonZero,
   round(COUNT(case when dmd_1wk = 0 then dmd_1wk end),2) AS NBR_ITEMS_1WK_Zero
FROM table;



回答3:


Method 1: Case Statement. This may be useful if you need to continue to process all rows (which a where clause would prevent).

 SELECT count(case when dmd_1wk = 0 then 0 else 1 end) as NonZeroCount FROM MyTable

Method 2: Where Clause.

 SELECT
   count(1) as NonZeroCount
 FROM
   MyTable
 WHERE
  dmd_1wk <> 0



回答4:


I'd like to offer another solution using NULLIF since COUNT won't count NULL values:

SELECT round(COUNT(NULLIF(dmd_1wk,0)),2) AS NBR_ITEMS_1WK
FROM table;

And here is the Fiddle.

Good luck.




回答5:


You can filter them.

SELECT round(COUNT(dmd_1wk),2) AS NBR_ITEMS_1WK
FROM table
WHERE dmd_1wk <> 0;


来源:https://stackoverflow.com/questions/14814137/how-to-count-the-rows-which-contains-non-zero-values-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!