2016-12-28 25 views
0

我正在計算曆年數據(以2015-2016年,2014-2015年等數據爲例)如果更高效地實現它,我想尋求專業知識一次批量或多次重複查詢所需的日期過濾。SQL效率日期範圍或單獨的表格

在此先感謝!

選項1:

select 
    id, 
    sum(case when year(getdate()) - year(txndate) between 5 and 6 then amt else 0 end) as amt_6_5, 
    ... 
    sum(case when year(getdate()) - year(txndate) between 0 and 1 then amt else 0 end) as amt_1_0, 
from 
    mytable 
group by 
    id 

選項2:

select 
    id, sum(amt) as amt_6_5 
from 
    mytable 
group by 
    id 
where 
    year(getdate()) - year(txndate) between 5 and 6 

... 

select 
    id, sum(amt) as amt_1_0 
from 
    mytable 
group by 
    id 
where 
    year(getdate()) - year(txndate) between 0 and 1 
+4

那麼,你可以嘗試兩個版本,看看你的自我...我打賭在版本1。 –

回答

0

這可能是幫助你,

WITH CTE 
AS 
(
    SELECT id, 
      (CASE WHEN year(getdate()) - year(txndate) BETWEEN 5 AND 6 THEN 'year_5-6' 
        WHEN year(getdate()) - year(txndate) BETWEEN 4 AND 5 THEN 'year_4-5' 
        ... 
        END) AS my_year, 
      amt 
    FROM mytable 
) 
SELECT id,my_year,sum(amt) 
FROM CTE 
GROUP BY id,my_year 

這裏,CTE裏面,只是分配一個合適的year_tag每個記錄(根據您的條件),然後選擇按該年份標籤分組的CTE摘要。

1

1. 除非您遇到資源問題,否則我會使用CASE版本。
雖然它對結果沒有影響,但在WHERE子句中過濾請求的時間段可能會有顯着的性能優勢。
2.您的期限定義創建重疊。

select id 
     ,sum(case when year(getdate()) - year(txndate) = 6 then amt else 0 end) as amt_6 
     -- ... 
     ,sum(case when year(getdate()) - year(txndate) = 0 then amt else 0 end) as amt_0 
where  txndate >= dateadd(year, datediff(year,0, getDate())-6, 0) 
from  mytable 
group by id