如何在PostgreSQL中的某一行的条件为真时立即退出CASE表达式 [英] How to exit case expression as soon as my condition becomes true for one of the row in postgresql
本文介绍了如何在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语句对于任何行都为TRUE,那么我应该从col6中获取其相应值并退出该CASE。
假设上述数据集中第一行的第一个CASE表达式为TRUE,则结果应为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, col2, 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;
这篇关于如何在PostgreSQL中的某一行的条件为真时立即退出CASE表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文