如何解决一旦我的条件对 postgresql 中的行之一变为真,如何退出 case 表达式
上面是我的配置文件,我有另一个数据集,其中与此配置文件匹配的必填列是 col1、col2 和 col3。
如果我上面的 3 列匹配,那么我对 col4 和 col5 使用 case 表达式。
Case when col5 = data from main dataset and col4 = data from main dataset then col6
Case when col5 = data from main dataset and col4 != data from main dataset then col6
Case when col5 != data from main dataset and col4 = data from main dataset then col6
Case when col5 != data from main dataset and col4 != data from main dataset then col6
以上case语句我不想为以上所有数据运行。如果我的第一个 case 语句对于任何行都为真,那么我应该从 col6 中获取其对应的值并退出 case。
假设我的第一个 case 表达式对于上面数据集中的第一行是真的,那么我应该得到结果为 4,并且 case 应该停止对其他行执行。
解决方法
您可以使用 order by
和 limit
:
select t.*
from t
where col1 = ? and col2 = ? and col3 = ?
order by (case when col5 = data and col4 = data then 1
when col5 = data then 2
when col4 = data then 3
else 4
end)
limit 1;
如果您希望每个 col1
/col2
/col3
组合都使用这个,请使用 distinct on
:
select distinct on (col1,col2,col3) t.*
from t
order by col1,col3,(case when col5 = data and col4 = data then 1
when col5 = data then 2
when col4 = data then 3
else 4
end)
limit 1;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。