我有一个表tb3,其中id,name,sal将使用select语句和city显示,只有当标志为'Y'时,描述字段才需要在同一个select语句中显示。我如何使用案例陈述?
id name sal city descrip flag
7 john 80000.00 Canada prog y
6 jone 90000.00 NY test y
3 san 70000.00 NY lead y
2 sam 70000.00 Cali sub n
1 sally 60000.00 Canada archi n
4 carl 70000.00 SA plain n
我需要做这样的事情......我知道这是错的,但对于一个样本请看看..
declare @test varchar(1)
select @test=flag from tb3
select id,name,case @test
when 'Y' then select city,descrip from tb3
when 'n' then 'inactive'
end as status from tb3
答案 0 :(得分:1)
SQL中的结果集有一组固定列 - 您不能逐行更改有多少列。如果您想要的内容是city
和descrip
列或inactive
,那么您必须将这两列合并为一个值:
select id,name,
CASE WHEN flag='Y' then city + ',' + descrip ELSE 'inactive' END as status
from tb3
或者,您可以将它们保留为两列,并在不合适时将其设置为NULL
:
select id,name,
CASE WHEN flag='Y' then city END as city,
CASE WHEN flag='Y' then descrip END as descrip
from tb3
答案 1 :(得分:0)
您可以直接使用标志栏的名称,如下所示
已更新:
select id,name ,case flag
when 'Y' then (city +' ' +descrip )
when 'N' then 'inactive'
end as status
from tb3
如何使用@test,因为它是varchar(1)变量,它将保持'Y'或'N',它只返回一种结果类型。如果最后一行标志值为'Y',那么所有行都将显示city,descrip,如果最后一行标志值为'N',则无论该行的标志列结果如何,它都将显示'inactive'。