在sum聚合上使用case语句

时间:2014-03-14 17:22:59

标签: sql

我试图在总和上运行一个案例,但似乎无法使其工作......基本上我想要返回1,如果列的总和是> 0 ...

SELECT Shop.Brands, Shop.Brand, Shop.T3, Shop.ShopName, Shop.Period 
CASE WHEN sum(PLData.Actuals) > 0 THEN 1 ELSE 0 END as Actuals,
CASE when sum(PLData.Budgets) > 0 THEN 1 ELSE 0 END as Budget,
CASE when sum(pldata.ForecastLedger) > 0 THEN 1 ELSE 0 END as Forecast
FROM SunFinance.dbo.Shop Shop LEFT OUTER JOIN SunFinance.dbo.PLData PLData ON Shop.T3 = PLData.Shop
WHERE Shop.BusinessType In ('CORPORATE','RETAIL','WHOLESALE')
AND PLData.Account Like '488%')
GROUP by shop.brand, shop.brands, shop.t3, shop.shopname, Shop.Period

我哪里错了?

1 个答案:

答案 0 :(得分:1)

如果您的DBMS不允许您在案例表达式中使用聚合,您可以尝试在内联视图中首先进行聚合,然后执行CASE表达式。

WITH RESULTS AS (
SELECT Shop.Brands
     , Shop.Brand
     , Shop.T3
     , Shop.ShopName
     , Shop.Period 
     , sum(PLData.Actuals) as Actuals
     , sum(PLData.Budgets) as Budget,
     , sum(pldata.ForecastLedger) as Forecast
FROM SunFinance.dbo.Shop Shop 
LEFT OUTER JOIN SunFinance.dbo.PLData PLData 
  ON Shop.T3 = PLData.Shop
WHERE Shop.BusinessType In ('CORPORATE','RETAIL','WHOLESALE')
      AND PLData.Account Like '488%'
GROUP by shop.brand, shop.brands, shop.t3, shop.shopname, Shop.Period
)
SELECT brands, brand, t3, shopname, period,
       case when actuals > 0 then 1 else 0 end as actuals, 
       case when budget > 0 then 1 else 0 end as budget, 
       case when forecast > 0 then 1 else 0 end as forecast
  FROM results