SQL运行总计 - 添加“缺失”值

时间:2013-03-16 23:20:05

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

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

如何让那些“失踪”的人在那里跑完全年?

1 个答案:

答案 0 :(得分:4)

您可以使用年份列表加入。

您可以使用&#34; Itzik的交叉连接CTE方法&#34;从这个问题的应答答案作为年度列表的来源:SQL, Auxiliary table of numbers

相关问题