我从发票表中选择年,月和净销售额。问题是如果特定月份下没有数据,那个月就没有行。你能帮助我吗?如果没有任何数据,净销售额应为零。
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)
提前致谢。
答案 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
动态生成日期,但我始终建议在物理上创建日历表并在此类查询中使用它