为空年选择0和

时间:2017-07-31 22:02:22

标签: sql sql-server sql-server-2008

这似乎是一个非常常见的问题,但我似乎找不到容易过渡到我的问题的答案。通常情况下,人们在寻找缺失月份的0,我的是多年。我只是在寻找过去10年中销售的每种产品,以显示10年的数量,或者如果没有,则显示0。

我的代码显示有销售的年份:

select upper(_producttype) as _product, YEAR(_date) as _year, 
coalesce(SUM(s._quantity * pu._usdperunit),0)  as _profit  
from QualityControl.dbo._Shipment s
join QualityControl.dbo._ProductUnits pu
on pu._prodid = s._productid
where year(GETDATE())-YEAR(_date) < 11
and upper(_producttype) != 'EQUIPMENT'
group by YEAR(_date), _producttype

order by  _producttype, YEAR(_date)

我的查询给出了过去10年(+当前)的列表:

select distinct YEAR(_date) as _year
from QualityControl.dbo._Shipment s
where year(GETDATE())-YEAR(_date) < 11
and _producttype != 'Equipment'
order by  YEAR(_date)

我尝试过将_profit设为0的联盟。我尝试过交叉连接,但此时似乎有太多列。在这一点上任何帮助将非常感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

如果不更改您的查询,您可以执行以下操作。

  • 只需将您的分组数据放入一个CTE
  • 岁的另一个
  • 创建第三个子集,即不同产品和年份的组合
  • 组合和数据之间的联接

WITH CTE_Data AS 
(
    select upper(_producttype) as _product, YEAR(_date) as _year, 
    coalesce(SUM(s._quantity * pu._usdperunit),0)  as _profit  
    from QualityControl.dbo._Shipment s
    join QualityControl.dbo._ProductUnits pu
    on pu._prodid = s._productid
    where year(GETDATE())-YEAR(_date) < 11
    and upper(_producttype) != 'EQUIPMENT'
    group by YEAR(_date), _producttype
)
, CTE_Years AS 
(
    select distinct YEAR(_date) as _year
    from QualityControl.dbo._Shipment s
    where year(GETDATE())-YEAR(_date) < 11
    and _producttype != 'Equipment'
)
, CTE_AllCombo AS 
(
    SELECT DISTINCT y._year, d._Product
    FROM CTE_Years y
    CROSS JOIN CTE_Data d
)
SELECT c._year, c._product, COALESCE(d._profit, 0) AS _profit
FROM CTE_AllCombo c
LEFT JOIN CTE_Data d ON d._year = c._year and d._product = c._product