SQL选择计数有多种情况

时间:2019-01-14 09:50:44

标签: sql aggregate-functions

我想要一列用于统计交易的列,其中itemtype包含两个指定值之一或location包含两个指定值之一。 前两列(项目类型和位置)给出了正确的数字,但第三列似乎计算了所有交易,与项目类型或位置无关。 我在做什么错了?

python -V
Python 3.6.7

which python
/usr/bin/python

4 个答案:

答案 0 :(得分:1)

对于最后一个,您可以使用SUM代替COUNT,如下所示-

SELECT 
  COUNT(CASE WHEN itemtype IN ('BARNTAL','STORSTIL') THEN 1 END) 'itemtype',
  COUNT(CASE WHEN location IN ('Lattlast','Appelhyllan') THEN 1 END) 'location',
  sum(CASE WHEN itemtype IN ('BARNTAL','STORSTIL') THEN 1 
  WHEN location IN ('Lattlast','Appelhyllan') THEN 1  
 END) 'total'  

FROM statistics

答案 1 :(得分:1)

您不需要添加ELSE部分:

SELECT COUNT(CASE WHEN itemtype IN ('BARNTAL','STORSTIL') THEN 1 END) AS itemtype,
       COUNT(CASE WHEN location IN ('Lattlast','Appelhyllan') THEN 1 END) AS location,
       COUNT(CASE WHEN itemtype IN ('BARNTAL','STORSTIL') THEN 1 
                  WHEN location IN ('Lattlast','Appelhyllan') THEN 1  
             END) AS total
FROM statistics;

答案 2 :(得分:1)

我认为,第三个条件如下

SELECT
COUNT(CASE WHEN itemtype IN ('BARNTAL','STORSTIL') OR location IN ('Lattlast','Appelhyllan') THEN 1 END) AS total
FROM statistics;

答案 3 :(得分:1)

COUNT不计算空值,这意味着它也从0部分“计算” ELSE。完全删除ELSE部分:

SELECT 
  COUNT(CASE WHEN itemtype IN ('BARNTAL','STORSTIL') THEN 1 END) 'itemtype',
  COUNT(CASE WHEN location IN ('Lattlast','Appelhyllan') THEN 1 END) 'location',
  COUNT(CASE WHEN itemtype IN ('BARNTAL','STORSTIL') THEN 1 
             WHEN location IN ('Lattlast','Appelhyllan') THEN 1
        END) 'total'  
FROM statistics