如何根据案例表达式

时间:2016-04-12 11:43:39

标签: sql oracle

我在SQL查询中有一个CASE表达式。我想基于案例表达式创建一个新列作为排名,并仅更新具有登录最大日期的行。

select A.*,
  CASE          
    WHEN A.COUNT = 1        
    THEN 'rank1'  
    -- I want to give the condition here saying update the row
    -- which has the latest login date with 'rank1' .. now it is
    -- updating all the row which has count as 1
    else 'rank2' end as Rank 
from table A

如何在上述代码中添加一个条件,只更新计数1和最新登录日期与同一注册中其他行相比的列?

结束表应如下所示:

count  regID   login        rank
1      221      10 april 16     rank1
1      221      9 april 16      rank2
1      221      8 april 16      rank2
1      366      8 march 16      rank2
1      366      1 feb 16        rank2
1      366      22 april 16     rank1

1 个答案:

答案 0 :(得分:6)

我认为您正在寻找row_number()

select A.*,
       (case when a.count = 1 and
                  row_number() over (partition by a.count, regid order by login desc) = 1
             then 'rank1'
             else 'rank2'
        end) as rank
from table A;