有人可以帮我解决下面的代码吗?
CASE Table1.Column1
WHEN 'a' THEN '1'
CASE Table2.Column2
WHEN 'b' THEN '2'
WHEN 'c' THEN '3'
ELSE '4'
END AS [Test],
我试图从Table1.Column1和Table2.Column2列中获取一个新列(Test)中的值。 感谢。
答案 0 :(得分:8)
CASE
还有另一种处理此问题的格式:
CASE WHEN Table1.Column1 = 'a' THEN '1'
WHEN Table2.Column2 = 'b' THEN '2'
WHEN Table2.Column2 = 'c' THEN '3'
ELSE '4'
END AS [Test],
此格式还允许多种条件,例如:WHEN a.col1 = 1 AND b.col1 = 2 THEN 'something'
,这可能会有所帮助。
答案 1 :(得分:0)
另一种方法是创建"字典"表:
DECLARE @dictTable TABLE(MyReplacement INT, MyKey VARCHAR(10))
INSERT INTO @dictTable (MyReplacement, MyKey)
VALUES(1, 'a'), (2, 'b')...
然后
SELECT t1.<Fields_List>, t2.<Fields_List>, t3.MyReplacement
FROM Table1 AS t1 (INNER|LEFT|RIGHT) JOIN Table2 AS t2 ON t1.Key = t2.ForeignKey
LEFT JOIN @dictTable AS t3 ON t1.Column1 = t2.MyKey AND t2.Column2 = t2.MyKey