sql - 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 仅获取第一行
解决方案
据我了解要求 - 因此,您希望从一组最多 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
推荐阅读
- delphi - 在 Delphi 中使用 TClientDataSet 验证我的表中是否存在数据
- visual-studio-code - 如何获取在 Visual Studio 代码上远程安装的扩展
- python - 在 Python 中比较字符串以查找匹配单词的最佳方法是什么?
- omnet++ - 如何在其他类中使用 sendDirect() 函数发送消息?
- symfony - 升级教义迁移
- .net-core - vs2019 C# 控制台应用程序未按预期运行
- batch-file - 使用 CMD 隐藏打开的程序
- windows - 通过 powershell 订购文件
- javascript - 添加 CSS 但保持内联样式
- python - 根据键值连接 Python 字典的记录(从 JSON 读取)并调整剩余键的值