Postgres案例查询问题

Ank*_*kit 1 postgresql case

我正在尝试编写一个postgres查询,它使用CASE语句.查询如下:

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 
Run Code Online (Sandbox Code Playgroud)

上面的查询显示语法错误 '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 
Run Code Online (Sandbox Code Playgroud)

请让我知道我做错了什么.

编辑:

THEN子句后面的值是动态的,它可能包含一个或多个值(来自多选框).我希望查询执行为

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 
Run Code Online (Sandbox Code Playgroud)

哪个运行完全正常,但问题是CASE没有返回我所需的字符串.

小智 5

您的查询应该是这样的,我希望这对您有用

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 
Run Code Online (Sandbox Code Playgroud)