2016-08-17 37 views
-1

我需要創建一個3周的平均值,只計算日期等於今天。本質上,代碼將像下面的那樣工作,但當然下面的代碼是不正確的。它說在關鍵字'ELSE'附近有一個不正確的語法。任何指導都將是非凡的。SQL 3周avearage與多個時,在一個案例聲明

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

如何*變量名(日期)*將是既等於GETDATE ()**和**小於GetDate()? – Blorgbeard

+0

@blorgbeard我需要它先確定今天是= Getdate()。一旦知道了,第二部分就是把getdate前21天的日期提前到getdate之前,並對它們進行平均。取消第一部分意味着每個日期的平均時間爲3周,因爲我只希望它爲getdate –

+0

您的僞代碼很混亂。你可以發佈一個小樣本表和預期的產出?這可能是澄清你想要什麼的更簡單的方法。 – Blorgbeard

回答

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 
    ...