1

我正在尝试编写一个带有 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 没有返回我所需的字符串。

4

4 回答 4

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 
于 2012-11-09T06:55:59.430 回答
2

'State' = 'State' 是重言式。您的意思是“State” = 'State',即“State”列的值等于字符串“State”吗?

于 2013-11-05T11:03:34.577 回答
1

由于您尝试使用,因此可以利用接受集合或数组IN的事实:IN

SELECT "State" AS x, count("Age Group") AS y
FROM test.smp_state_survey
WHERE "State" IN (CASE
  WHEN 'State' = 'State' THEN ARRAY['State 1','State 2','State 3']
  WHEN 'State' = 'District' THEN ARRAY['State 1']
END) 
GROUP BY x
ORDER BY x,y 

或使用@user1327246 的改写,将IN测试推送到CASE语句中。

于 2012-11-09T06:56:44.023 回答
0

一个案例不能有多个值。

这就是问题

WHEN 'State' = 'State' THEN 'State 1','State 2','State 3'
于 2012-11-09T06:32:33.993 回答