2017-01-13 57 views
0

我一直堅持sql查詢來帶來想要的數據。我有以下表格 enter image description hereSQL Server 2008多列過濾器

我試過cte表,但沒有工作。如果可用,我需要獲取源'O',否則如上面的結果表中的最大序列'T'。

select district 
    , id 
    , building 
    , year 
    , date 
    , period 
    , sequence 
    , source from GetAttData gt with (nolock) where sequence in (select max(sequence) from GetAttData with (nolock) 
       where district = gt.district 
        and building = gt.building 
        and year = gt.year 
        and id= gt.id 
       group by district, id, building, year, date, period) 
    and source = 'O' 

回答

3
select 
    district, id, building, year, date, period, sequence, source 
from (
    select district, id, building, year, date, period, sequence, source, 
    row_number() over(partition by district, id, building, year, date, period 
        order by case when source = 'O' then 0 else 1 end, sequence desc 
        ) as takeme 
) foo 
where takeme = 1 
+0

我喜歡的列名「takeme」 ......馬爾科 – marcothesane

+0

非常感謝你Gserg,你救我的一天。 – JOZO