分组但包含“缺失”值

时间:2011-01-25 20:13:38

标签: tsql sql-server-2000

假设我有以下内容。

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

让我们说它通常只返回两种颜色。拉出所有三种颜色的最佳方法是什么,包含0表示缺失值?

全联盟?

4 个答案:

答案 0 :(得分:2)

是的,Union All可能是您最好的选择。

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

答案 1 :(得分:2)

将GROUP移动到具有更多列的条件SUM中?

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

为此通过一桌。 UNION ALL或子查询方法(在其他答案中)每个子句触摸一次表=有点慢。

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

如果必须存在所有颜色,为什么不将它们显示为列?

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

否则,请使用@ JohnK813回答。