2012-09-17 25 views
1

我有一個包含「狀態」整數字段的重複數據集。我想知道是否有某種方法來設置MAX()聚合函數來將某些值「設置」爲較低的優先級。如何在查詢中爲MAX函數設置自定義的「排名」順序?

我最終要對這個數據集運行一個查詢來對重複進行分組,並選擇'最大'狀態值不是'6'但返回6如果它是值和那裏這條記錄不重複。

使用MAX是最好的方式去做這件事還是有更好的方法嗎?

回答

2
select coalesce(max(case when id = 6 then null else id end), max(id)) 
from (select 6 id union all select 2) a 

我與民主黨同意的改進建議,謝謝@Dems

select coalesce(max(nullif(id, 6)), max(id)) 
from (select 6 id union all select 2) a 

如果 '身份證' 永遠不能爲null,MAX(ID),可以用6

+1

'NULLIF(ID,6)'?如果OP確認'id'永遠不能是'NULL',那麼'COALESCE'的第二個參數可以是'6'。 – MatBailie

0
declare @T table 
(
    Grp int, 
    Val int 
) 

insert into @T values 
(2, 1), 
(2, 2), 
(2, 6), 
(6, 6), 
(7, 2), 
(7, 6), 
(7, 7) 

select Val 
from 
    (
    select Val, 
      row_number() over(partition by Grp 
          order by case when Val = 6 
             then 1 
             else 0 
             end, Val desc) as rn 
    from @T 
) as T 
where T.rn = 1 
取代

結果:

Val 
----------- 
2 
6 
7