gpt4 book ai didi

SQL 在 CASE 语句为真时返回另一个表的值

转载 作者:行者123 更新时间:2023-11-29 12:36:39 26 4
gpt4 key购买 nike

我想编写一个 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";

最佳答案

您可以只使用一组 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";

关于SQL 在 CASE 语句为真时返回另一个表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com