Aet*_*rix 7 sql t-sql sql-server
我有一张看起来像这样的表:
ID Type Value
A Z01 10
A Z09 20
B Z01 30
C Z01 40
D Z09 50
E Z10 60
Run Code Online (Sandbox Code Playgroud)
对于每个 ID,我想检索一个值。理想情况下,该值应来自类型为 Z01 的行。但是,如果 Z01 不可用,我会选择 Z09。如果什么都没有,我想什么都不选。
结果如下所示:
Id Type Value
A Z01 10
B Z01 30
C Z01 40
D Z09 50
Run Code Online (Sandbox Code Playgroud)
如何使用 T-SQL 完成此操作?
这应该给你你想要的:
select *
from table t
where 1 = case
when t.type = 'Z01'
then 1
when t.type = 'Z09'
and not exists (select 1 from table where id = t.id and type = 'Z01')
then 1
else 0
end
Run Code Online (Sandbox Code Playgroud)
另一种使用更常见的方法是(重写CASE表达式):
select *
from table
where type = 'Z01'
OR (type = 'Z09' and not exists (select 1 from table where id = t.id and type = 'Z01'))
Run Code Online (Sandbox Code Playgroud)
一个明显的sargable方法(这将使您的查询在您的表上使用适当的索引,如果存在的话)是:
select *
from table
where type = `Z01`
union all
select *
from table
where type = `Z09`
and not exists (select 1 from table where id = t.id and type = 'Z01')
Run Code Online (Sandbox Code Playgroud)
当我说索引时,我指的是type列上的非聚集索引。