我想编写一个SQL语句,该语句根据CASE语句返回一个值,该语句有三种可能的结果。
1)如果列值以'C0'开头,则它返回表中两列的串联
2)如果列以'L0'开头,则取该行中另一列(_PARENT_PROJECT_NUMBER)中的值,并查看该值是否位于另一个表中。如果不是,则返回值_PARENT_PROJECT_NUMBER。
3)如果_PARENT_PROJECT_NUMBER确实驻留在另一个表中,则返回另一个表“Rollup_Project_Mapping”中“Rollup_Project”列中的值。
我在下面写的声明工作正常,但第12行"Rollup_Project_Mapping"."Rollup_Project"
除外,如果在另一个表中找到_PARENT_PROJECT_NUMBER,我希望它返回另一个表的值。以下是错误消息:
ERROR: syntax error at or near "FROM"
LINE 12: FROM "Rollup_Project_Mapping"."Rollup_Project"
当CASE语句的这部分为真时,有谁知道如何在其他表中返回值?
SELECT
CASE
WHEN LEFT("_PROJECT_NUMBER",2)='C0' THEN
'('||"_PROJECT_NUMBER"||') '||"_PROJECT_DESCRIPTION"
WHEN LEFT("_PROJECT_NUMBER",2)='L0' THEN
CASE
WHEN (SELECT "Rollup_Project" FROM "Project_Rollup_Mapping" WHERE "PA_ACCOUNTED_TEST"."_PARENT_PROJECT_NUMBER" = "Project_Rollup_Mapping"."Project") IS NOT NULL THEN
"Rollup_Project_Mapping"."Rollup_Project"
ELSE "_PARENT_PROJECT_NUMBER"
END
END AS Rollup_Project2
FROM "PA_ACCOUNTED_TEST";
答案 0 :(得分:4)
您只能使用一组WHEN
/ THEN
语句和EXISTS
:
SELECT (CASE WHEN LEFT("_PROJECT_NUMBER",2) = 'C0'
THEN '('||"_PROJECT_NUMBER"||') '||"_PROJECT_DESCRIPTION"
WHEN LEFT("_PROJECT_NUMBER",2) = 'L0' AND
EXISTS (SELECT "Rollup_Project" FROM "Project_Rollup_Mapping" WHERE "PA_ACCOUNTED_TEST"."_PARENT_PROJECT_NUMBER" = "Project_Rollup_Mapping"."Project")
THEN (SELECT "Rollup_Project" FROM "Project_Rollup_Mapping" WHERE "PA_ACCOUNTED_TEST"."_PARENT_PROJECT_NUMBER" = "Project_Rollup_Mapping"."Project")
ELSE "_PARENT_PROJECT_NUMBER"
END) AS Rollup_Project2
FROM "PA_ACCOUNTED_TEST";
答案 1 :(得分:0)
我根据@Gordon Linoff的答案修改了原始的SQL语句,以防有人想要它作为另一种选择:
SELECT
CASE
WHEN LEFT("_PROJECT_NUMBER",2)='C0' THEN
'('||"_PROJECT_NUMBER"||') '||"_PROJECT_DESCRIPTION"
WHEN LEFT("_PROJECT_NUMBER",2)='L0' AND (SELECT "Rollup_Project" FROM "Project_Rollup_Mapping" WHERE "PA_ACCOUNTED_TEST"."_PARENT_PROJECT_NUMBER" = "Project_Rollup_Mapping"."Project") IS NOT NULL THEN
(SELECT "Rollup_Project" FROM "Project_Rollup_Mapping" WHERE "PA_ACCOUNTED_TEST"."_PARENT_PROJECT_NUMBER" = "Project_Rollup_Mapping"."Project")
ELSE "_PARENT_PROJECT_NUMBER"
END AS Rollup_Project2
FROM "PA_ACCOUNTED_TEST";