Sql 使用Group By和Rollup创建期间到日期的摘要

Sql 使用Group By和Rollup创建期间到日期的摘要,sql,sql-server,group-by,rollup,Sql,Sql Server,Group By,Rollup,我的数据库(SQL Server 2016)中有一个表,其中包含我正在运行的进程的度量错误。每隔10分钟采集一次样本,因此数据如下所示: Timestamp Error '18 Oct 2019 14:00:00', 0.200 '18 Oct 2019 14:10:00', - 0.175 '18 Oct 2019 14:20:00', - 0.150 '18 Oct 2019 14:30:00', 0.183 我可以很容易地使用group

我的数据库(SQL Server 2016)中有一个表,其中包含我正在运行的进程的度量错误。每隔10分钟采集一次样本,因此数据如下所示:

Timestamp                  Error

'18 Oct 2019 14:00:00',    0.200
'18 Oct 2019 14:10:00',  - 0.175
'18 Oct 2019 14:20:00',  - 0.150
'18 Oct 2019 14:30:00',    0.183
我可以很容易地使用group by和rollup按月、周、日等汇总这些数据。但这样做时,我将得到所有天、周、月的汇总

如何编写查询以显示“最新”摘要,即

Average Error Over Period   Error

Today                        0.175
This Week                   -0.002
This Month                   0.201
This Year                    0.053
All Time                     0.027

用于计算错误的查询相当繁重,因此我不希望多次运行它

通常,我会将其作为单独的列执行:

select avg(error) as total,
       avg(case when timestamp > cast(getdate() as date) then error end) as today,
       avg(case when timestamp > dateadd(day, -6, cast(getdate() as date) then error end) as this_week,
       . . .
from t;
我不知道你对“今天”、“本周”等的确切定义是什么。上面是条件聚合的一个示例

这只经过
t
一次

如果您希望将其放在单独的行中,可以取消填充数据。我的首选方法使用交叉应用

with t as (
      select avg(error) as total,
             avg(case when timestamp > cast(getdate() as date) then error end) as today,
             avg(case when timestamp > dateadd(day, -6, cast(getdate() as date) then error end) as this_week,
           . . .
      from t
     )
select v.*
from t cross apply
     (values ('Total', total), ('Today', today), ('This week', this_week), . . .
     ) v(period, error);

当你看到它的时候,它是如此的明显。非常感谢。