使用Group By计算多个值

时间:2015-02-14 17:30:05

标签: sql oracle

如果这个问题含糊不清,我很抱歉,我是SQL的新手并且遇到了一些麻烦。我试图找出每个体重组中的人数。计算该数字并显示每个班级的数量。

我认为我的问题在于THEN表达式。我是否需要为每个权重组创建一个变量以进行比较?

谢谢

SELECT 
(CASE WHEN pl_weight <180 THEN 1
WHEN pl_weight >=180 AND pl_weight <200 THEN 2
WHEN pl_weight >=200 AND pl_weight <220 THEN 3
ELSE 4 END),
count(1) "Less than 280", count(2)"180-200", count(3)"200-220",count(4)"More than 220"  
FROM dl_player
GROUP BY (CASE WHEN pl_weight <180 THEN 1
WHEN pl_weight >=180 AND pl_weight <200 THEN 2
WHEN pl_weight >=200 AND pl_weight <220 THEN 3
ELSE 4
END));

2 个答案:

答案 0 :(得分:1)

这样做的一种方法是使用这样的条件聚合:

SELECT 
    SUM(CASE WHEN "pl_weight" <180 THEN 1 ELSE 0 END) AS "Less than 280",
    SUM(CASE WHEN "pl_weight" >=180 AND "pl_weight" <200 THEN 1 ELSE 0 END) AS "180-200",
    SUM(CASE WHEN "pl_weight" >=200 AND "pl_weight" <220 THEN 1 ELSE 0 END) AS "200-220",
    SUM(CASE WHEN "pl_weight" >=220 THEN 1 ELSE 0 END) AS "More than 220"  
FROM dl_player

示例结果:

| LESS THAN 280 | 180-200 | 200-220 | MORE THAN 220 |
|---------------|---------|---------|---------------|
|             4 |       1 |       3 |             3 |

Sample SQL Fiddle

答案 1 :(得分:1)

COUNT()没有按照你想要的方式工作;它计算行数,或者更具体地说,内部值不为NULL的行数。您可以使用条件聚合执行此操作,如@ jpw的答案,或者您可以使用子查询执行此操作:

SELECT weight, COUNT(*) FROM (
    SELECT CASE WHEN pl_weight <180 THEN "Less than 180"
        WHEN pl_weight >=180 AND pl_weight <200 THEN "180-200"
        WHEN pl_weight >=200 AND pl_weight <220 THEN "200-220"
        ELSE "More than 220" END AS weight
      FROM dl_player
) GROUP BY weight;

顺便说一句,我不确定你是否注意到了,但在最后的案例中你有一个一个一个错误。对于 220或更多的值,它将返回4More than 220