多重错误在哪里?

时间:2014-09-05 17:19:49

标签: mysql sql

SELECT 
   count(ProductID) as CountAllProducts,
   count(CASE WHEN PriceType = '1' THEN ProductID ELSE 0 END) as CountPriceType1,
   count(CASE WHEN PriceType = '2' THEN ProductID ELSE 0 END) as CountPriceType2
FROM Products

我们得不到正确的结果:

CountAllProducts   CountPriceType1   CountPriceType2
     10                 10                 10

但应该是:

CountAllProducts   CountPriceType1   CountPriceType2
     10                 10                 0

请告诉我哪里有错误?

2 个答案:

答案 0 :(得分:2)

对于参数为非null的任何行,COUNT()计数为1.

换句话说,零的数量与1的数量或香蕉或其他任何数量相同。

你可能想要这个:

SELECT 
   count(ProductID) as CountAllProducts,
   count(CASE WHEN PriceType = '1' THEN ProductID ELSE NULL END) as CountPriceType1,
   count(CASE WHEN PriceType = '2' THEN ProductID ELSE NULL END) as CountPriceType2
FROM Products

您可以稍微缩短一点,因为CASE如果值不匹配则隐式返回NULL。

SELECT 
   count(ProductID) as CountAllProducts,
   count(CASE WHEN PriceType = '1' THEN ProductID END) as CountPriceType1,
   count(CASE WHEN PriceType = '2' THEN ProductID END) as CountPriceType2
FROM Products

另一种方法是使用SUM()而不是COUNT(),并确保SUM()的参数是1(计算它)或0(不计算它)。因为一堆1和0的总和等于1的计数。

SELECT 
   count(ProductID) as CountAllProducts,
   SUM(CASE WHEN PriceType = '1' THEN 1 ELSE 0 END) as CountPriceType1,
   SUM(CASE WHEN PriceType = '2' THEN 1 ELSE 0 END) as CountPriceType2
FROM Products

答案 1 :(得分:1)

count计算非空值,因此即使计算0

SELECT 
   count(ProductID) as CountAllProducts,
   count(CASE WHEN PriceType = '1' THEN ProductID ELSE NULL END) as CountPriceType1,
   count(CASE WHEN PriceType = '2' THEN ProductID ELSE NULL END) as CountPriceType2
FROM Products

SELECT 
   count(ProductID) as CountAllProducts,
   sum(PriceType = '1') as CountPriceType1,
   sum(PriceType = '2') as CountPriceType2
FROM Products