2016-01-06 74 views
1

我想使用group by語句獲取列的「max」字符值,但不是默認的字母順序,我想設置max將使用的自定義順序。Max的自定義訂單()

表1:

ID | TYPE 
-----+------- 
    1 | A 
    1 | B 
    1 | C 
    2 | A 
    2 | B 

欲組由ID和的C,A,B.預期結果的順序獲得最大的(類型):

ID | MAX_TYPE 
-----+----------- 
    1 | C 
    2 | A 

回答

1

而是翻譯來回,使用窗口功能:

select t.* 
from (select t.*, 
      row_number() over (partition by id 
           order by (case when type = 'C' then 1 
               when type = 'A' then 2 
               when type = 'B' then 3 
              end) as seqnum 
     from t 
    ) t 
where seqnum = 1; 

根據這些值是什麼樣子,你也可以簡化這個使用字符串函數:

select t.* 
from (select t.*, 
      row_number() over (partition by id 
           order by position(type, 'CAB')) as seqnum 
     from t 
    ) t 
where seqnum = 1; 
1
select 
    id, 
    case 
     max(
      case max_type 
       when 'C' then 3 when 'A' then 2 when 'B' then 1 
      end 
     ) 
     when 3 then 'C' when 2 then 'A' when 1 then 'B' 
    end as max_type 
from T 
group by id 

轉換爲一個值排在max()之後,然後轉回原始值。

如果你也想訂購由該值的結果,那麼你可以添加:

order by 
    max(
     case max_type 
      when 'C' then 3 when 'A' then 2 when 'B' then 1 
     end 
    ) desc 

有些平臺需要排序列被包含在輸出中。我不確定PostgreSql是否是其中之一。對Gordon的回答沒有異議,但是如果你也需要使用另一個窗口函數來計算排序順序的話。