How sum with case conditional statement works in sql

天大地大妈咪最大 提交于 2019-12-01 01:28:55

Presumably, this is the part that you are struggling to understand:

  select deptno,
         sum(case when jobname = 'Analyst' then 1 else 0 end) as numAnalysts
  from employees
  group by deptno

This is a simple aggregation query, really. What the query is doing is:

  • Look at each row in employees
  • If jobname is 'Analyst' then assign the value of 1 (this is the case statement. Otherwise, assign a value of0`.
  • Aggregate by department, summing the value just calculated. This has the effect of counting the number of analysts.

case is an expression that returns a value. The sum() is simply adding up that value for each group.

Lets try to split the problem in 2 parts.

First, let suppose you want a field saying if the jobname is 'Analyst' or not.

SELECT
  deptno,
  CASE WHEN jobname = 'Analyst' THEN 1 ELSE 0 END AS IsAnalyst
FROM
  employees

This query is going to return 0 for all the jobname that are no 'Analyst' and 1 for all the ones that are 'Analyst'

At this point you will have something like this

deptno IsAnalyst
1      1
1      0
1      0
2      0
2      1
2      1
2      1
2      0

Second, You want to summarize this information by department

SELECT
  deptno,
  SUM(CASE WHEN jobname = 'Analyst' THEN 1 ELSE 0 END) AS numAnalysts
FROM
  employees
GROUP BY
  deptno

You are applying a sum to all those value and grouping by deptno.

At this point (I removed the order by from the query to simplify it) you will have the following output

deptno numAnalysts
1      1
2      3

I think that an example is worth a thousand words

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!