WHERE子句中的distinct和case

时间:2016-03-23 12:39:21

标签: sql postgresql rank

我可以在where子句之后使用case。以下是我的询问。

谢谢,

select unit_id, law_id, risk, count(risk) as crr
                            from schema.table1 
                            group by unit_id, law_id, risk
          order by crr desc, risk desc

结果

unit_id |law_id | risk      | crr
----------------------------------
|   1   | 3     |Significant| 3 
|   1   | 3     |Limited    | 3
|   3   | 2     |Significant| 1
|   1   | 1     |Significant| 1
|   2   | 2     |Medium     | 1
|   1   | 3     |Critical   | 1

当我对它们进行排名时

select unit_id, law_id, a.risk, 
                            rank() OVER (PARTITION BY unit_id, law_id ORDER BY crr DESC, risk DESC ) as rank
            from (select unit_id, law_id, risk, count(risk) as crr
                            from schema.table1 
                            group by unit_id, law_id, risk
          order by crr desc, risk desc                              
           ) a

结果

unit_id |law_id | risk      | rank
----------------------------------
|   1   | 1     |Significant| 1 
|   1   | 3     |Significant| 1
|   1   | 3     |Limited    | 2
|   1   | 3     |Critical   | 3
|   2   | 2     |Medium     | 1
|   3   | 2     |Significant| 1

我的查询得到以下结果。但我希望得到所有排名为1而忽略排名1并获得排名(无论排名是什么),如果有任何上述结果。 我希望得到类似下面的结果。

select unit_id, law_id, risk FROM                
            (select unit_id, law_id, a.risk, 
                            rank() OVER (PARTITION BY unit_id, law_id ORDER BY crr DESC, risk DESC ) as rank
            from (select unit_id, law_id, risk, count(risk) as crr
            from schema.table1 group by unit_id, law_id, risk
          order by crr desc, risk desc      
           ) a  )b WHERE rank = 1 or risk = 'Critical'

实际结果

unit_id |law_id | risk      
----------------------------
|   1   | 1     |Significant
|   1   | 3     |Significant
|   1   | 3     |Critical
|   2   | 2     |Medium    
|   3   | 2     |Significant

预期结果

unit_id |law_id | risk      
----------------------------
|   1   | 1     |Significant
|   1   | 3     |Critical
|   2   | 2     |Medium    
|   3   | 2     |Significant

1 个答案:

答案 0 :(得分:1)

尝试使用CASE EXPRESSION RANK()中的ORDER BY

select unit_id, law_id, risk FROM                
            (select unit_id, law_id, a.risk, 
                     rank() OVER (PARTITION BY unit_id, law_id 
                                  ORDER BY CASE WHEN risk = 'Critical' then 1 else 0 end DESC, crr DESC, risk DESC ) as rank
            from (select unit_id, law_id, risk, count(risk) as crr
            from schema.table1 group by unit_id, law_id, risk
          order by crr desc, risk desc      
           ) a  )b WHERE rank = 1 

这样,critical将首先排名为1,其余的将按您的逻辑排名。