首页 > 解决方案 > IF 列中第二行的值 = X 选择第二个

问题描述

我的查询

select * from
(select * from
item
where (level_value = 'AT' or level_value='250004')
and effective_date < SYSDATE 
AND (expiration_date is null OR expiration_date > SYSDATE)
order by effective_date DESC)
where item_id = '12345'

我想检查 item_id =12345 IF 列级别值中第二行的值 = '250004' 仅显示第二行,如果第一行中的值和列中的第二行 level_value 相同 - 仅获取第一行

如何使用案例/那么做到这一点?

例如: 数据库

如果 level_value = 250004 在查询结果的屏幕截图中位于第二行,则获取第二行。如果查询结果中的第一行 ='AT' 和第二行 ='AT' 中的 level_value 仅获取第一行

标签: sqloracle

解决方案


据我了解要求 - 因此,您希望从一组最多 2 条记录中获得一条记录 - 如果我理解正确,“250004”记录是更好的选择,“AT”是备用计划,那么以下建议将适用于您,利用左连接和 oracle nvl 功能

    select 
    nvl(other.item_id,at.item_id) as item_id,
    nvl(other. level_value,at. level_value) as level_value,
    nvl(other.effective_date,at.effective_date) as effective_date,
    nvl(other.expiration_date,at.expiration_date) as expiration_date 
    from
        (select item_id,
        level_value,
        effective_date,
        expiration_date from item 
        where level_value = 'AT'
        AND nvl(expiration_date, SYSDATE-1)<SYSDATE) at
    left join 
        (select item_id,
        level_value,
        effective_date,
        expiration_date from item 
        where level_value = '250004'
        AND nvl(expiration_date, SYSDATE-1)<SYSDATE
        ) other
    on (at.item_id = other.item_id)
where nvl(other.item_id,at.item_id) = '12345'
order by effective_date DESC

推荐阅读