我想编写一个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,则我希望它返回另一张表的值。这是错误消息:
"Rollup_Project_Mapping"."Rollup_Project"
ERROR: syntax error at or near "FROM" LINE 12: FROM "Rollup_Project_Mapping"."Rollup_Project"
当CASE语句的这一部分为true时,有人知道如何在另一个表中返回该值吗?
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";
您只能使用一组WHEN/THEN语句和EXISTS:
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";