SELECTSQL数据按日期填月

SELECT SQL data based on date, fill month

我正在从发票中选择年份、月份和净销售额 table。问题是,如果特定月份下没有数据,则该月份将没有行。你能帮助我吗?如果没有任何数据,净销售额应该为零。

SELECT 
    DATEPART(year, date) as 'year', 
    DATEPART(month, date) as 'month', 
    SUM(netsales) as netsales 
FROM invoice 
WHERE 
    date >= '2015-01-01' 
    AND date <= '2016-12-31' 
GROUP BY 
    DATEPART(year, date), 
    DATEPART(month, date)

提前致谢。

你需要 calendar table 和 left join

;with calendar as
(
select cast('2015-01-01' as date) as dates -- start date
union all
select dateadd(mm,1,dates) from cte where dates < '2016-12-31' -- end date
)

SELECT 
    DATEPART(year, c.dates) as 'year', 
    DATEPART(month, c.dates) as 'month', 
    SUM(netsales) as netsales 
FROM calendar C left join invoice i on c.dates = cast(i.[date] as date)
GROUP BY 
    DATEPART(year, date), 
    DATEPART(month, date)

我已经使用 Recursive CTE 即时生成日期,但我总是建议创建一个物理日历 table 并在此类查询中使用它