sql - 如何基于案例表达式中的条件更新行

标签 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

最佳答案

我认为您正在寻找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;

关于sql - 如何基于案例表达式中的条件更新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36572313/

相关文章:

sql - 如何使用 group by 语句 + max 函数加速 SQL 查询?

c# - 为什么在 linq-to-sql select 中比较 UTF16 字符串时会得到错误的结果?

sql - 替换每个分区的 NULL 值

sql - 涉及三个表的复杂更新

sql - 显示 Oracle SQL 中表的所有约束的名称

java - 如何在 Spring 中设置 Oracle 加密属性?

sql - 如何与 Doctrine 建立联合?

sql - 您应该将 SQL 存储过程存储在源代码管理中吗?

sql - 从数字中删除零

java - 对两个非空字段添加唯一约束