How sum with case conditional statement works in sql

前端 未结 2 581
鱼传尺愫
鱼传尺愫 2021-01-06 20:08

The other day, I gave an answer to this question but then other user solved that problem with sum + case conditional statement to add one edge condition in result. So, the q

2条回答
  •  感动是毒
    2021-01-06 20:56

    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.

提交回复
热议问题