从MySQL查询中计算不同的0值

时间:2018-04-26 16:49:32

标签: sql count

我正在尝试进行此查询:

SELECT    monthPosted,
          sector,
          COUNT(sumaAbas) as abasNum,
          SUM(sumaAbas) as abas,
          COUNT(usdAmount) AS totalNum,
          SUM(usdAmount) AS total
FROM      DatosSpend
WHERE     negotiableProcGl='Y'
GROUP BY  sector

我遇到的问题是COUNT(usdAmount)正在计算其中也包含0的所有值。

如何忽略值的计数= 0?

2 个答案:

答案 0 :(得分:1)

聚合函数忽略null。您可以使用case表达式将0转换为null,从而跳过它们。 E.g:

SELECT   monthPosted,
         sector, 
         COUNT(sumaAbas) as abasNum, 
         SUM(sumaAbas) as abas, 
         COUNT(CASE usdAmount WHEN 0 THEN NULL ELSE 1 END) AS totalNum, 
         SUM(usdAmount) AS total 
FROM     DatosSpend 
WHERE    negotiableProcGl = 'Y' 
GROUP BY sector

答案 1 :(得分:1)

You can just simply exclude the 0 values in the WHERE clause:

WHERE negotiableProcGl='Y' AND value != 0

Where value is your column name