这似乎是一个非常常见的问题,但我似乎找不到容易过渡到我的问题的答案。通常情况下,人们在寻找缺失月份的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的联盟。我尝试过交叉连接,但此时似乎有太多列。在这一点上任何帮助将非常感激。
谢谢。
答案 0 :(得分:0)
如果不更改您的查询,您可以执行以下操作。
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