日期范围或单独表上的SQL效率

时间:2016-12-28 07:37:21

标签: sql sql-server processing-efficiency

我正在计算一年中的历史金额(例如2015-2016,2014-2015等)我想寻求专业知识,如果它在一批中更有效率或多次重复查询按所需日期过滤。

提前致谢!

选项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

2 个答案:

答案 0 :(得分: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

答案 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,然后选择按该year_tag分组的CTE摘要。