我正在尝试开发一个对表执行select操作的存储过程。存储过程有4个输入: Input1、Input2、Input3、Input4。
表有4列: Col1、Col2、Col3、Col4。
要求是如果所有选择都没有匹配,我们需要忽略它并选择pick next one:
使用案例:
Select *
from table
where Col1=Input1
and Col2=Input2
and Col3=Input3
and Col4=Input4;如果由于Col2不等于Input2而导致条件没有返回,select需要忽略它,并尝试匹配其他条件,如:
Select *
from table
where Col1=Input1
and Col3=Input3
and Col4=Input4;它应该是这样,直到响应的最后一个可能选项:
Select *
from table
where Col1=Input1;如果有办法请协助,并提前表示感谢。
发布于 2021-04-08 16:54:28
正如评论中提到的,这个问题有点含糊,所以我担心任何答案也会有点含糊。你可以这样做:
select top 1 *,
case when Coll=input1 then 1 else 0 end as match1,
case when Col2=input2 then 1 else 0 end as match2,
case when Col3=input3 then 1 else 0 end as match3,
case when Col4=input4 then 1 else 0 end as match4
from table
order by match1+match2+match3+match4 desc这是假设SQL服务器作为DBMS (例如,如果是Oracle,您可能需要使用LIMIT而不是TOP ),并且我还假设列在匹配方面具有相同的权重。此外,我假设您只需要一个最佳匹配,如果不是,您可能需要对顶部进行一些更改和/或使用where子句。最后,如果您的列和/或输入可以为空,则可能需要使用isnull()。
发布于 2021-04-09 23:24:26
嗯。。。一种方法是:
select t.*
from (select t.*,
sum(case when condition1 then 1 else 0 end) over () as c_1,
sum(case when condition1 and condition2 then 1 else 0 end) over () as c_12,
sum(case when condition1 and condition2 and condition3 then 1 else 0 end) over () as c_123,
sum(case when condition1 and condition2 and condition3 and condition4 then 1 else 0 end) over () as c_1234
from t
) t
where (c_1234 > 0 and condition1 and condition2 and condition3 and condition4) or
(c_1234 = 0 and c_123 > 0 and condition1 and condition2 and condition3) and
(c_123 = 0 and c_12 > 0 and condition1 and condition2 ) and
(c_12 = 0 and c_1 > 0 and condition1 ) ;根据条件和其他考虑因素--例如您是否只期望一行--可能会有更简单的方法。
https://stackoverflow.com/questions/66996503
复制相似问题