SQL Server 2008 R2
示例数据:
ownership exact_opening_date
Type1 3/1/2002
Type1 1/4/2004
Owned 3/1/2002
Owned 3/31/2003
Owned 6/30/2004
我想按所有权类型逐年获得运行总数,但即使该年没有值,也要保持运行总数:
ownership open_date run_total
Type 1 2002 1
Type 1 2003 1 <-- here's my trouble
Type 1 2004 2
我可以得到运行总计,但是当我在那一年实际上没有值时,我不确定如何包括该运行总计。
这就是我现在正在做的事情:
WITH cte (
ownership
,open_date
,ct
)
AS (
SELECT ownership
,year(exact_opening_date) AS open_date
,count(*) AS ct
FROM studio_master
GROUP BY ownership
,year(exact_opening_date)
)
SELECT d1.ownership
,d1.open_date
,sum(d2.ct) AS run_total
FROM cte d1
LEFT JOIN cte d2 ON d1.open_date >= d2.open_date
AND d1.ownership = d2.ownership
GROUP BY d1.ownership
,d1.open_date
,d1.ct
ORDER BY d1.ownership
,d1.open_date
我如何在那里获得那些“失踪”的总年数?