如何从SQL Server中的CASE语句中选择第一个匹配的行

时间:2017-12-13 17:37:41

标签: sql sql-server select

从SQL Server中的一个简单表中,有两列,如下所示

Key   Value
------------
A     5000
B     NULL
C     6000

我希望以B,A,C的顺序获取第一条记录(即获取B的值,如果为null,则为A的值,如果为null,则为C的值),其中Value不为空。从上面的列表中我希望输出为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

2 个答案:

答案 0 :(得分:2)

嗯,嗯。 。 。一种方法使用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",但可能不适用于所有字符串。

答案 1 :(得分:2)

您可以使用where子句忽略null value,按自定义排序(使用case表达式)排序,然后选择{{1}行:

top 1
相关问题