2016-03-20 124 views
1

我想編寫一個SQL語句,該語句基於具有三種可能結果的CASE語句返回一個值。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"; 

回答

3

只需使用一組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"; 
+0

謝謝!完美工作! – christopheralan88

0

我適應原來的SQL語句基於@Gordon Linoff答案的情況下,任何人合作想讓它作爲另一種選擇:

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";