我需要创建一个3周平均值,仅在日期等于今天时计算。基本上代码将像下面的那样工作,但当然下面的代码不正确。它说关键字'ELSE'附近的语法不正确。任何指导都是惊人的。
CASE WHEN
*Variable Name(Date)* = GETDATE()
THEN
CASE WHEN *Variable Name(Date)* >= GETDATE()-21 AND *Variable Name(Date)* < GETDATE()
THEN
SUM(*Variable Name(Minutes)*/3 ELSE 0 END AS ThreeWeekAvg
答案 0 :(得分:0)
select
...
from
<your table> t
cross apply (
select sum(minutes) / 3e as ThreeWeekAvg
from <your table> t2
where
t.<date> = cast(getdate() as date)
and t2.<date> >= dateadd(day, -21, t.<date>)
and t2.<date> < t.<date>
);
通过“变量名称”我假设你在谈论列。您还可以在新版本的SQL Server上使用sum() over (range ...)
。
虽然我相信我的上述尝试是有效的,但这是另一种方法,其子查询看起来更接近您尝试的原因:
select
...
case when *Variable Name(Date)* = getdate() then (
select sum(*Variable Name(Minutes)*) / 3e
from ...
where *Variable Name(Date)* >= getdate() - 21 and *Variable Name(Date)* < getdate()
) as ThreeWeekAvg
from
...