[英]How to select first matching row from the CASE statement in SQL Server
从SQL Server中的一个简单表中,如下两列所示
Key Value
------------
A 5000
B NULL
C 6000
我想按B,A,C
的顺序获取第一条记录(即获取B的值,如果为null,则获取A的值,如果为null,则获取C的值),其中Value
不为null。 从上面的列表中,我希望输出为5000
我正在尝试使用此代码-没有任何运气:
SELECT
CASE
WHEN [Key] = 'B' AND Value IS NOT NULL
THEN Value
WHEN [Key] = 'A' AND Value IS NOT NULL
THEN Value
WHEN [Key] = 'C' AND Value IS NOT NULL
THEN Value
END
FROM
temporary
嗯。 。 。 一种方法使用coalesce()
:
select coalesce(max(case when [Key] = 'B' then value end),
max(case when [Key] = 'A' then value end),
max(case when [Key] = 'C' then value end)
)
from temporary;
但是,我想我会这样做:
select top 1 t.value
from temporary t
where value is not null and [Key] in ('A', 'B', 'C')
order by charindex([Key], 'B,A,C');
请注意, order by
只是获取首选排序的简写。 它适用于“ A”,“ B”和“ C”,但可能无法推广到所有字符串。
您可以使用where
子句省略null
value
,通过自定义排序(使用case
表达式)进行排序,并仅获取top 1
行:
SELECT TOP 1 value
FROM mytable
WHERE value IS NOT NULL
ORDER BY CASE key WHEN 'B' THEN 0
WHEN 'A' THEN 1
WHEN 'C' THEN 2
ELSE 3
END ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.