如何在sql中的group by之后对每一行应用过滤器

时间:2017-04-29 09:57:12

标签: sql conditional-aggregation

我有一张桌子 - 表= EMP

eno ename designation sal   mgr  deptno
1   aaa   salesman    7000  2    10
2   bbb   manager     17000 3    10
3   ccc   president   40000 null 30
4   ddd   clerk       5000  5    20
5   eee   manager     20000 3    20

问)每个工作有多少员工的收入超过10000?

我想要结果 -

designation  count(*)
salesman     0
manager      2
clerk        0
president    1

查询 -

SELECT designation, count(*) FROM emp WHERE sal>10000 GROUP BY designation;

获得结果 -

designation count(*)
manager     2
president   1

请告诉我如何在逐个子句后对每一行应用过滤器?

2 个答案:

答案 0 :(得分:1)

SELECT designation, sum(case when sal > 10000 then 1 else 0 end) as count
FROM emp 
GROUP BY designation;

答案 1 :(得分:0)

使用SUM AND GROUP BY函数:

  SELECT designation, SUM(CASE WHEN sal > 10000 THEN 1 ELSE 0 END) AS count
  FROM Your_table 
  GROUP BY designation;