我需要在select中添加一个case语句,但我似乎无法正确使用语法,有人可以帮忙吗?
SELECT
uuid = pnt.ID
,extras = (CASE (SELECT pnt.TypeID as [type], pnt.Source as source)
WHEN source = 7 THEN 'a'
WHEN source = 1 AND [type] = 0 THEN 'b'
WHEN source = 8 THEN 'c'
WHEN source = 2 AND [type] = 0 THEN 'd'
WHEN source = 3 AND [type] IN (5,6,7,8) THEN 'e'
ELSE NULL
END)
FROM
Mydata as pnt
存在多个问题,案例中的选择不正确,条件源= 7错误,AND的组合条件错误,使用IN的条件不正确。
我使用Multiple Criteria In Case Statement的答案作为案例陈述的基础。
答案 0 :(得分:3)
SELECT
@uuid = pnt.ID
,@extras = (CASE WHEN source = 7 THEN
'a'
WHEN source = 1 AND [type] = 0 THEN
'b'
WHEN source = 8 THEN
'c'
WHEN source = 2 AND [type] =0 THEN
'd'
WHEN source = 3 AND [type] IN (5,6,7,8) THEN
'e'
ELSE NULL
END
)
FROM
Mydata as pnt
答案 1 :(得分:2)
SELECT
PNT.ID AS UUID
, CASE
WHEN PNT.source = 7 THEN 'a'
WHEN PNT.source = 1 AND PNT.[type] = 0 THEN 'b'
WHEN PNT.source = 8 THEN 'c'
WHEN PNT.source = 2 AND PNT.[type] = 0 THEN 'd'
WHEN PNT.source = 3 AND PNT.[type] IN (5, 6, 7, 8) THEN 'e'
ELSE NULL
END AS EXTRAS
FROM Mydata AS PNT
由于您已经在表格Mydata中工作,case expression
可以访问[source]和[type]中保存的值而无需添加选择。
我已经将列别名放在每个列定义的末尾,我相信数据库通常比使用=更为普遍支持。
答案 2 :(得分:2)
有两种类型的案例陈述:
https://msdn.microsoft.com/en-us/library/ms144841(v=sql.105).aspx
在您的脚本中,您可以"混合"他们,所以你的脚本不起作用。 这可能是一个很好的解决方案:
SELECT
pnt.ID
,CASE
WHEN pnt.source = 7 THEN 'a'
WHEN pnt.source = 1 AND pnt.TypeID = 0 THEN 'b'
WHEN pnt.source = 8 THEN 'c'
WHEN pnt.source = 2 AND pnt.TypeID = 0 THEN 'd'
WHEN pnt.source = 3 AND pnt.TypeID IN (5, 6, 7, 8) THEN 'e'
ELSE NULL
END
FROM
@Mydata AS pnt
警告! 如果你需要填充单个变量(uuid,extras),你必须确保你的查询结果只有1个记录
答案 3 :(得分:1)
SELECT ID As uuid, CASE WHEN Source = 7 THEN
'a'
WHEN Source = 1 AND TypeID= 0 THEN
'b'
WHEN Source = 8 THEN
'c'
WHEN Source = 2 AND TypeID= 0 THEN
'd'
WHEN Source = 3 AND TypeID IN (5,6,7,8) THEN
'e'
ELSE
NULL
END
AS extras FROM Mydata