Group By but include “missing” values

前端 未结 4 2059
醉梦人生
醉梦人生 2021-01-25 15:13

Suppose I have the following.

select
  case
    when fcompany = \'Acme\' then \'Red\'
    when fcompany = \'Acme Rockets\' then \'Blue\'
    else \'Green\'
  en         


        
4条回答
  •  星月不相逢
    2021-01-25 15:48

    Move the GROUP into a conditional SUM with more columns?

    select
      sum(CASE WHEN fcompany = 'Acme'
                         THEN fann_sales ELSE 0 END) AS redsales,
      sum(CASE WHEN fcompany = 'Acme Rockets'
                         THEN fann_sales ELSE 0 END) AS bluesales
      sum(CASE WHEN fcompany NOT IN ('Acme Rockets', 'Acme')
                         THEN fann_sales ELSE 0 END) AS greensales
    FROM
      slcdpm
    

    One pass over the table for this. A UNION ALL or subquery approach (in other answers) will touch the table once per clause = somewhat slower.

提交回复
热议问题