1
SELECT "public"."mv_tags_per_org"."count" AS "count", "public"."mv_tags_per_org"."tag_name" AS "Tag Name",
CASE 
    WHEN "public"."mv_tags_per_org"."ngo_id" = 30 then 'SSS'
    WHEN "public"."mv_tags_per_org"."ngo_id" = 33 then 'PF'
    WHEN "public"."mv_tags_per_org"."ngo_id" = 34 then 'DS'
    ELSE 'Maybe'
END AS "NPO"
FROM "public"."mv_tags_per_org"

WHERE "NPO???" = "SSS"

上面你可以看到我的代码。当您删除“WHERE”功能时,它当前正在返回我想要的输出。我正在添加“WHERE”函数并尝试访问我创建的名为“NPO”的新列。在 SQL 编辑器中似乎该列不存在,但在运行查询时它确实存在。我如何访问它?

谢谢!

4

2 回答 2

1

将您的查询包含在一个“表表达式”中,这样​​您就可以生成一个命名列。然后你可以在WHERE子句中使用它:

select *
from ( -- table expression 'x' starts here
  SELECT
    "public"."mv_tags_per_org"."count" AS "count",
    "public"."mv_tags_per_org"."tag_name" AS "Tag Name",
  CASE 
    WHEN "public"."mv_tags_per_org"."ngo_id" = 30 then 'SSS'
    WHEN "public"."mv_tags_per_org"."ngo_id" = 33 then 'PF'
    WHEN "public"."mv_tags_per_org"."ngo_id" = 34 then 'DS'
    ELSE 'Maybe'
  END AS "NPO"
  FROM "public"."mv_tags_per_org"
) x
WHERE "NPO" = 'SSS'

注意:“表表达式”也被不同的团队称为“派生表”和“内联视图”。

于 2020-03-03T15:07:30.090 回答
0

WHERE子句不能与该子句中定义的列别名相关SELECT(因为前者在后者之前被评估)。

这对您的用例并不重要,可以简化为:

SELECT 
    "public"."mv_tags_per_org"."count" AS "count",    
    "public"."mv_tags_per_org"."tag_name" AS "Tag Name",
CASE 
    WHEN "public"."mv_tags_per_org"."ngo_id" = 30 then 'SSS'
    WHEN "public"."mv_tags_per_org"."ngo_id" = 33 then 'PF'
    WHEN "public"."mv_tags_per_org"."ngo_id" = 34 then 'DS'
    ELSE 'Maybe'
END AS "NPO"
FROM "public"."mv_tags_per_org"
WHERE "public"."mv_tags_per_org"."ngo_id" = 30
于 2020-03-03T15:09:37.240 回答