我想做类似的事情:
CASE WHEN name = 'John'
THEN
CASE WHEN surname = 'BBBB' THEN XYZ END AS surname
CASE WHEN surname = 'CCCC' THEN XYZXYZ END AS second_surname
ELSE
CASE WHEN surname = 'BBBB' THEN ABCDEF END AS third_surname
CASE WHEN surname = 'CCCC' THEN ABCDEFABCDEF END AS fourth_surname
END,
但是我变成了错误:ORA-00905:缺少关键字
我该如何解决?
答案 0 :(得分:3)
它们都是不同的列,因此每列都需要一个CASE。
CASE WHEN name = 'John' AND surname = 'BBBB' THEN XYZ END AS surname
CASE WHEN name = 'John' AND surname = 'CCCC' THEN XYZXYZ END AS second_surname
CASE WHEN name <> 'John' AND surname = 'BBBB' THEN ABCDEF END AS third_surname
CASE WHEN name <> 'John' AND surname = 'CCCC' THEN ABCDEFABCDEF END AS fourth_surname
如果您想要一栏,那么类似@TimBiegeleisen的答案将起作用。
正如@MTO指出的,我的不处理空值。这样可以解决
CASE WHEN COALESCE(name,'Not John') <> 'John' AND surname = 'BBBB' THEN ABCDEF END AS third_surname
CASE WHEN COALESCE(name,'Not John') <> 'John' AND surname = 'CCCC' THEN ABCDEFABCDEF END AS fourth_surname
答案 1 :(得分:3)
我认为这里的问题是您对别名的错误使用。外部CASE
表达式表示一个单个标量,因此最后一个外部END
采用单个别名,并且内部的所有内容都不应该别名。因此,您可以尝试以下版本:
CASE WHEN name = 'John'
THEN
CASE WHEN surname = 'BBBB' THEN XYZ
WHEN surname = 'CCCC' THEN XYZXYZ END
ELSE
CASE WHEN surname = 'BBBB' THEN ABCDEF
WHEN surname = 'CCCC' THEN ABCDEFABCDEF END
END AS some_alias
但是,您也可以使用单个级别CASE
表达式来表达逻辑:
CASE WHEN name = 'John' AND surname = 'BBBB' THEN XYZ
WHEN name = 'John' AND surname = 'CCCC' THEN XYZXYZ
WHEN (name <> 'John' OR name IS NULL) AND surname = 'BBBB' THEN ABCDEF
WHEN (name <> 'John' OR name IS NULL) AND surname = 'CCCC' THEN ABCDEFABCDEF END AS some_alias