【问题标题】:Sum last 12 months data when there is no data for few months in between当中间几个月没有数据时,总结过去 12 个月的数据
【发布时间】:2020-02-27 19:42:29
【问题描述】:

尝试汇总过去 12 个月的数据,但有几个月没有数据,因此数据集中完全缺少月份名称:

考虑到缺失月份数据为 0,如何计算 2019 年 1 月至 2020 年 1 月之间的最近 12 个月数据?

【问题讨论】:

  • 我正在使用 Sql Server
  • 为什么名为“日期”的列是字符串?更糟糕的是,为什么它有日期以外的数据?这是一个巨大的设计问题。
  • 是的,我知道。日期字段的目的是标记数据集上的总计,例如去年总计、当年总计、YTD 等,我们现在需要使用此表显示过去 3、6 和 12 个月的趋势。我们所拥有的只是月份和年份
  • 你能告诉我们你想要的输出吗?抱歉,我已经读过你的问题几次了,如果你试图显示缺失的月份(间隔-and-islands 问题)在查询结果中,或两者兼而有之。
  • 不使用图片的原因是here

标签: sql sql-server database tsql


【解决方案1】:

在 SQL Server 中你可以使用apply:

select t.*, t2.total1
from t outer apply
     (select sum(t2.total) as total1
      from t t2
      where t2.date <= t.date and
            t2.date > dateadd(month, -12, t.date)
     ) t2;

由于您的日期列已损坏,您可以改用:

select t.*, t2.total1
from t outer apply
     (select sum(t2.total) as total1
      from t t2
      where t2.year * 12 + t2.month <= t.year * 12 + t.month and
            t2.year * 12 + t2.month > t.year * 12 + t.month - 12
     ) t2;

【讨论】:

  • 'Date' 字段是字符串,其中也有其他文本。我可以用来计算的唯一字段是“月”和“年”
  • @sql_dev1802 。 . .修复你的数据模型!当你提出问题时,你应该让你的问题更清楚。
【解决方案2】:

您可以使用 DATEFROMPARTS 函数将月份和年份转换为日期:

select sum(total1) as total
from table
where datefromparts(year,month,1) between '01Jan2019' and '01Jan2020'

如果您想要过去 12 个月的动态结果,那么:

select sum(total1) as total
from table
where datefromparts(year,month,1) between DATEADD(month,-13,GETDATE()) and GETDATE()

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-11
    • 2020-10-09
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多