【问题标题】:SELECT SQL data based on date, fill month根据日期选择 SQL 数据,填写月份
【发布时间】:2016-10-19 17:45:30
【问题描述】:

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

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)

提前致谢。

【问题讨论】:

  • @a_horse_with_no_name MS SQL

标签: sql sql-server datepart


【解决方案1】:

您需要一个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 即时生成日期,但我总是建议物理创建日历表并在此类查询中使用它

【讨论】:

  • 是的,这是一个很好的方法。由于很多公司需要基于日历月的报告,我认为有一个只有月份的表格(开始日期、结束日期、天数、日历年、月份数)也很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2021-10-31
  • 2020-07-02
相关资源
最近更新 更多