两个日期之间的SQL Server总和数据按日期分组

时间:2020-07-06 12:21:09

标签: sql sql-server

我的表中有以下数据:

eb          |anz
05.03.2020  | 2
06.03.2020  | 3
07.03.2020  | 1
08.03.2020  | 9
09.03.2020  | 10
10.03.2020  | 2
11.03.2020  | 20
12.03.2020  | 25

现在,我需要对每个日期的特定范围内的值求和。 例如“ 12.03.2020”:我想对日期“ 12.03.2020”的3月12日,11日,10日和9日的值求和。另外,我想在3月9日之前对其他四个值进行求和,然后将摘要1除以摘要2进行选择。

所以我的计算将是:(25 + 20 + 2 + 10)/(9 + 1 + 3 + 2)= 3.8 我想在表格中输出日期和每个日期的计算值。

我尝试对每个日期(例如3月9日至12日)的第一组求和,但是输出与表中的数据相同。

select
eb,
sum(anz)
from (select eb, count(*) as anz from myTable where eb != '' group by eb) tmp
where 
convert(date, eb, 104) >= dateadd(day,-3,convert(datetime, eb, 104)) 
and convert(date, eb, 104) <= convert(date, eb, 104)
group by eb
order by convert(date, eb, 104)

该条件似乎已被忽略。你对我有什么建议吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

让我假设data已正确存储为date,那么您可以使用窗口函数:

select t.*,
       (sum(anz) over (order by eb rows between 3 preceding and current row) /
        sum(anz) over (order by eb rows between 8 preceding and 4 preceding)
       )
from t;

请注意,如果value是整数,请使用* 1.0 /避免整数除法。

此外,这还假设您每个日期都有数据。