Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 当两个月之间没有数据时,求最后12个月数据的总和_Sql_Sql Server_Database_Tsql - Fatal编程技术网

Sql 当两个月之间没有数据时,求最后12个月数据的总和

Sql 当两个月之间没有数据时,求最后12个月数据的总和,sql,sql-server,database,tsql,Sql,Sql Server,Database,Tsql,试图对过去12个月的数据求和,但有几个月没有数据,因此数据集中完全缺少月份名称: 考虑到缺失的月份数据为0,我如何计算2019年1月至2020年1月之间最近12个月的数据 在SQL Server中,您可以使用应用: 由于日期列已断开,您可以改为使用: select t.*, t2.total1 from t outer apply (select sum(t2.total) as total1 from t t2 where t2.year * 12 + t2.

试图对过去12个月的数据求和,但有几个月没有数据,因此数据集中完全缺少月份名称:

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

在SQL Server中,您可以使用应用:

由于日期列已断开,您可以改为使用:

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;

您可以使用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()

希望这有帮助。

我正在使用Sql Server为什么名为Date的列是字符串?更糟糕的是,为什么它有日期以外的数据?这是一个巨大的设计问题。是的,我知道。日期字段用于标记数据集上的总计,如去年总计、本年总计、年初至今等。我们要求使用此表显示最近3个月、6个月和12个月的趋势。我们只有月数和年数,你能告诉我们你想要的产量吗?抱歉,我已经读了您的问题好几次了,我不确定您是否正在尝试找出如何指定日期范围,因为您的日期和年份表示方式不一致,您是否正在尝试在查询结果中显示缺少的月份、间隔和孤岛问题,或者两者都有。不使用图像的原因是。'date'字段为string,它还有其他的文本。我唯一可以用来计算这个的字段是'Month'和'Year'@sql\u dev1802。修正你的数据模型!当你问问题的时候,你应该把问题弄清楚。
select sum(total1) as total
from table
where datefromparts(year,month,1) between DATEADD(month,-13,GETDATE()) and GETDATE()