Group By but include “missing” values

眉间皱痕 提交于 2019-12-02 17:21:37

问题


Suppose I have the following.

select
  case
    when fcompany = 'Acme' then 'Red'
    when fcompany = 'Acme Rockets' then 'Blue'
    else 'Green'
  end
    Color
,sum(fann_sales)
FROM
  slcdpm
group by
  case
    when fcompany = 'Acme' then 'Red'
    when fcompany = 'Acme Rockets' then 'Blue'
    else 'Green'
  end

Let's say it often returns with only two colors. What's the best way to pull all three colors and include 0 for the missing value?

Union All?


回答1:


Yes, Union All may be your best bet.

SELECT 'red' AS Color, sum(fann_sales) FROM slcdpm WHERE fcompany = 'Acme' GROUP BY fcompany
UNION ALL
SELECT 'blue' AS Color, sum(fann_sales) FROM slcdpm WHERE fcompany = 'Acme Rockets' GROUP BY fcompany
UNION ALL
SELECT 'green' AS Color, sum(fann_sales) FROM slcdpm WHERE fcompany <> 'Acme' AND fcompany <> 'Acme Rockets' GROUP BY fcompany



回答2:


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.




回答3:


Try this:

SELECT  b.Color, 
                sum(fann_sales) 
 FROM   (
                SELECT  case
                                    when fcompany = 'Acme' then 'Red'
                                    when fcompany = 'Acme Rockets' then 'Blue'
                                    else 'Green'
                                end
                                Color,
                                fann_sales
                    FROM slcdpm
            ) a  RIGHT JOIN 
            (
                SELECT 'Red' AS Color
                UNION ALL
                SELECT 'Blue' AS Color
                UNION ALL
                SELECT 'Green' AS Color
            ) b
        ON a.Color = b.Color            
 GROUP BY  b.Color



回答4:


If all colors must be present, why not present them as columns?

SELECT
    (SELECT sum(fann_sales) FROM slcdpm WHERE fcompany = 'Acme') AS RedSum,
    (SELECT sum(fann_sales) FROM slcdpm WHERE fcompany = 'Acme Rockets') AS BlueSum,
    (SELECT sum(fann_sales) FROM slcdpm WHERE fcompany <> 'Acme' AND fcompany <> 'Acme Rockets') AS GreenSum

Otherwise, just go with @JohnK813 answer.



来源:https://stackoverflow.com/questions/4798324/group-by-but-include-missing-values

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