2016-01-05 97 views
1

我已經繼承了一些數據庫,其中一些表包含多個相同的值。SQL在具有多個相同值的表上加入

表阿
助劑(PK),RowId的,價值,CREATEDATE

錶行
RowId的(PK)

表A(20M條目)含有大量的RowId的的多個相同的條目和值(CreateDate會有所不同),每個RowId通常有20個相同的條目。我想要做這個查詢:

select Row.RowId, DistinctA.Value 
from Row 
left join (select distinct RowId, Value from A) DistinctA 
on DistinctA.RowId=Row.RowId 

什麼是最好的方法?

回答

0

這是你想要的嗎?

select a.* 
from (select a.*, 
      row_number() over (partition by rowid, value order by createdate desc) as seqnum 
     from a 
    ) a 
where seqnum = 1; 

這返回最近的行中每個組合(使用order by createdate asc最舊行)。

+0

是的,看起來不錯!這會比原始查詢有更好的性能嗎? – Peter

+0

您的原始查詢沒有意義(至少就您要實現的內容而言)。 –

相關問題