根据日期,填充月份选择SQL数据

时间:2016-10-19 17:45:30

标签: sql sql-server datepart

我从发票表中选择年,月和净销售额。问题是如果特定月份下没有数据,那个月就没有行。你能帮助我吗?如果没有任何数据,净销售额应为零。

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)

提前致谢。

1 个答案:

答案 0 :(得分:2)

您需要calendar表和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动态生成日期,但我始终建议在物理上创建日历表并在此类查询中使用它