我正在尝试编写一个带有 CASE 语句的 postgres 查询。查询如下:
SELECT "State" AS x, count("Age Group") AS y from test.smp_state_survey where "State" IN
(CASE
WHEN 'State' = 'State' THEN 'State 1','State 2','State 3'
WHEN 'State' = 'District' THEN 'State 1'
END)
group by x ORDER BY x,y
上面的查询在 'State' = 'State'
处显示语法错误
然而,当我执行以下查询时,我得到了适当的结果:
SELECT "State" AS x, count("Age Group") AS y from test.smp_state_survey where "State" IN
(CASE
WHEN 'State' = 'State' THEN 'State 1'
WHEN 'State' = 'District' THEN 'State 1'
END)
group by x ORDER BY x,y
请让我知道我做错了什么。
编辑:
THEN 子句后的值是动态的,它可能包含 1 个或多个值(来自多选框)。我希望查询执行为
SELECT "State" AS x, count("Age Group") AS y from test.smp_state_survey where "State" IN
('State 1','State 2','State 3')
group by x ORDER BY x,y
运行得很好,但问题是 CASE 没有返回我需要的字符串。
最佳答案
你的查询应该是这样的,我希望这对你有用
SELECT "State" AS x, count("Age Group") AS y from test.smp_state_survey where
CASE
WHEN 'State' = 'State' THEN "State" IN ('State 1' ,'State 3')
WHEN 'State' = 'District' THEN "State" IN ('District 1')
END
group by x ORDER BY x,y
关于postgresql - Postgres案例查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13303183/