【问题标题】:SQL : SELF JOIN Vs RANK, Which will be faster in this scenario?SQL:SELF JOIN Vs RANK,在这种情况下哪个更快?
【发布时间】:2014-11-14 02:04:20
【问题描述】:

我确定这是一个非常简单的 SQL 查询问题。这是我尝试使用时间戳列 (As_Of) 查询具有最后更新值的 ID 的表的模型

ID      Value  As_of

1173    156    20090601

1173    173    20081201

1173    307    20080901

1173    305    20080601

127     209    20090301

127     103    20081201

127     113    20080901

127     113    20080601

1271    166    20090201

1271    172    20081201

1271    170    20080901

1271    180    20080601
...

我的结果应该是这样的

ID      Value    As_of

1173    156      20090601

127     209      20090301

1271    166      20090201

我应该使用哪个选项来完成? SELF JOIN 还是 RANK()? 请就这两种方法的性能向我提出一些建议。哪个更快? 我听说 SELF JOIN 会降低查询的性能。

排名():

SELECT ID, Value, As_Of, RANK() OVER(PARTITION BY ID ORDER BY As_of DESC) 'RNK'
FROM Table

and by filtering using the column having RANK value 1

自加入:

SELECT ID, Value,As_of 
from Table a inner join 
          (SELECT ID, MAX(As_of) as As_of 
          from Table group by ID) b 
on a.ID=b.ID and a.As_of = b.As_of

【问题讨论】:

  • 你考虑过基准测试吗?

标签: sql sql-server performance join


【解决方案1】:

您应该在数据上尝试这两种方法,看看哪种方法更快。我可能怀疑rank() 方法会更快,因为它消除了显式的join,但没有什么比真正的测试更能确定的了。

顺便说一下,你应该试试第三种方法:

select id, value, as_of
from table t
where not exists (select 1 from table t2 where t2.id = t.id and t2.as_of > t.as_of);

有时,这种方法也可以有很好的性能。

【讨论】:

    【解决方案2】:

    当您拥有大量数据时,交叉应用或加入效果更好

    Select t1.id, t1.value, t1.as_of
    from table t
    cross apply(Select top 1 * from table t1 where t.id = t1.id order by as_of desc)t1
    where t.as_of = t1.as_of
    

    【讨论】:

      【解决方案3】:
      SELECT ID,VALUE,AS_OF 
          FROM Table T1 
          WHERE 1=(
                SELECT COUNT(*) 
                FROM Table T2 
                WHERE T1.ID=T2.ID AND T2.AS_OF>=T1.AS_OF
          )
      

      这也可能有效..

      【讨论】:

        猜你喜欢
        • 2013-06-09
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 2013-04-17
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多