仅返回RANK()之后的最小值

时间:2018-06-24 11:07:47

标签: postgresql window-functions rank

我使用以下方法创建了某些“案例”:

RANK() OVER(ORDER BY name, A, B, some_value) as case_id

现在,我需要在每个case_id中创建等级,其中名称只能出现一次,并且最低等级应分配给最低some_value。

这是数据示例:

data

和所需的输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

Select * from ( 

    Select Name, A, B, some_value, case_id 
    , ROWNO() over (partition by case_id, Name order by some_value) as R1
    from (
        Select 'SF' as Name, 'y' as A, 'n' as B, 120 as some_value, 1 as case_id
        union all Select 'NY' as Name, 'y' as A, 'n' as B, 150 as some_value, 1 as case_id
        union all Select 'LA' as Name, 'y' as A, 'n' as B, 155 as some_value, 1 as case_id
        union all Select 'SF' as Name, 'y' as A, 'n' as B, 160 as some_value, 1 as case_id
        union all Select 'SF' as Name, 'n' as A, 'y' as B, 110 as some_value, 5 as case_id
        union all Select 'NY' as Name, 'n' as A, 'y' as B, 120 as some_value, 5 as case_id
        union all Select 'LA' as Name, 'n' as A, 'y' as B, 125 as some_value, 5 as case_id
        union all Select 'LA' as Name, 'n' as A, 'y' as B, 140 as some_value, 5 as case_id
        union all Select 'NY' as Name, 'n' as A, 'y' as B, 155 as some_value, 5 as case_id
    ) testdata

    ) data
Where R1 = 1
order by case_id, some_value