伪:
如果条件为真,则返回结果并且不寻找下一个条件。
如果条件为假,则检查下一个条件。
等等...我有大约 6 个要按层次结构顺序检查。
案例检查每个条件,因此它不会在第一个条件处停止,而是继续,并且集合中有多个 true,但是,我只想要第一个!
Nest IFF 也给了我同样的东西。 (多个答案)
IIF((t.testkey = 141 AND wordsalad <3) OR (t.testkey = 141 AND wordsalad>10),'Found it 1',
iif(t.testkey = 821 AND wordsalad <20,'Found it 2',
iif(t.testkey = 725 AND wordsalad<1.0030,'Fouind it 3',
iif(t.testkey = 725 AND wordsalad>1.025,'Found it 4',
iif(t.testkey = 810 AND wordsalad<10,'Found it 5',
iif(t.testkey = 809 AND word salad<10,'found it 6',
'Didn't find it')))))),
我该如何编写,以便它在找到第一个条件后停止而不继续?
这是针对案例:
CASE
WHEN (t.testkey = 141 AND wordsalad <3) OR (t.testkey = 141 AND
wordsalad >10.0)) then 'Found it 1'
WHEN (t.testkey = 821 AND wordsald <20) then 'Found it 2'
WHEN (t.testkey = 725 AND wordsalad <1.0030) then 'Found it 3'
WHEN (t.testkey = 725 AND wordsalad >1.025) then 'Found it 4'
WHEN (t.testkey = 810 AND wordsalad <10) then 'Found it 5'
WHEN (t.testkey = 809 AND wordsalad <10) then 'Found it 6'
Else 'Didn't find it'
END AS [Conditions2]
数据看起来像这样:
Test | TestKey | wordsalad |
Test1| TestKey141 | 10.2 |
Test2| TestKey821 | 4 |
test3| TestKey725 | 0 |
等等..
我有点猜测你到底在追求什么,但也许是这样的(?):
create table sometable (id int, testkey int, wordsalad decimal(18,6))
insert sometable (id, testkey, wordsalad) values (1, 821, 17)
insert sometable (id, testkey, wordsalad) values (1, 725, 0.5)
GO
-- return the row that matches the most preferred condition.
-- If none of the rows matched any of the conditions, then no row is returned.
select top 1 * from sometable t
cross apply (
select
CASE
WHEN (t.testkey = 141 AND wordsalad <3) OR (t.testkey = 141 AND
wordsalad >10.0) then 1 -- most preferred condition
WHEN (t.testkey = 821 AND wordsalad <20) then 2
WHEN (t.testkey = 725 AND wordsalad <1.0030) then 3
WHEN (t.testkey = 725 AND wordsalad >1.025) then 4
WHEN (t.testkey = 810 AND wordsalad <10) then 5
WHEN (t.testkey = 809 AND wordsalad <10) then 6 -- least preferred condition
Else NULL -- not matched
END AS cond
) c
where c.cond IS NOT NULL
order by c.cond