sql - SQL - 选择子句中的子选择 - 如何创建决定唯一性逻辑的列
问题描述
我正在尝试编写子选择,它将遍历返回的数据,然后检查所有状态,然后决定唯一性逻辑。
有没有办法找出以下?
- 如果任何数据具有“活动”状态,第一个将被标记为 1,其他所有数据都为 0
- 如果没有“活动”状态,则第一个“过期”状态将标记为 1,其他所有状态都标记为 0
- 如果没有“活动”和“过期”状态,那么首先“进行中”将被标记为 1,其他所有内容都标记为 0
我试图这样写,但我需要在一个案例陈述中使用它
SELECT a.id, a.status,
,(SELECT
CASE WHEN b.STATUS = 'Active' THEN 1 ELSE 0 END
CASE WHEN b.STATUS = 'Expired' THEN 1 ELSE 0 END
FROM b.TABLE
WHERE a.id=b.id )AS unique
FROM my.TABLE
结果应该看起来像https://i.stack.imgur.com/qCA74.png过期案例的图片
提前感谢您的任何提示。
解决方案
使用窗口函数:
select t.*,
(case when row_number() over (partition by id
order by case status when 'Active' then 1 when 'Expired' then 2 else 3 end
) = 1
then 1 else 0
end) as unique_flag
from my.table t;
推荐阅读
- javascript - SVG 元素是垂直居中的,我不希望它是
- java - 尝试从 .txt 文件中获取输入,并将其放入双向链表
- python - 我在 Windows PC 上构建了一个 Flask 应用程序,但现在想在 macOS 中工作。为什么“烧瓶运行”会产生错误:“zsh:找不到命令:烧瓶”
- python - 在一个 Django 视图中组合两个单独的表单?
- java - 在 Java 中使用 ASCII 作为板坐标
- c - c程序的未定义参考Clion
- octave - regexp does not work as expected in Octave
- php - 正则表达式删除字符串上的字母或数字之前和之后的所有内容
- mongodb - 如何使用 php 7.3(Windows 10)在 symfony4 上安装 mongodb-odm?
- moodle - 将moodle 2.7.1 升级到php 7.0 和mysql 5.6。但是如果升级mysql就无法连接mysql 8.0