SQL Server 2008多列过滤器

时间:2017-01-13 22:22:01

标签: sql sql-server-2008

我坚持使用sql查询来获取想要的数据。我有桌子如下 enter image description here

我尝试过cte table但是没有用。我需要获取源'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' 

1 个答案:

答案 0 :(得分: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