【问题标题】:SQL Efficiency on Date Range or Separate Tables日期范围或单独表的 SQL 效率
【发布时间】:2016-12-28 07:37:20
【问题描述】:

我正在从表中计算历史金额(例如 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

【问题讨论】:

  • 好吧,你可以试试这两个版本,然后自己看看……我赌的是版本 1。

标签: sql sql-server processing-efficiency


【解决方案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

【讨论】:

    【解决方案2】:

    这可能对你有帮助,

    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 的摘要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多