2017-01-13 10 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