我正在尝试使用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子句后面的值是动态的,它可能包含一个或多个值(来自多选框)。我希望查询以
的形式执行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没有返回我所需的字符串。
答案 0 :(得分: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
答案 1 :(得分:2)
'州'='州'是同义反复。 你的意思是“State”='State',即“State”列的值等于字符串'State'吗?
答案 2 :(得分: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
语句。
答案 3 :(得分:0)
单个案例不能有多个值。
这就是问题
WHEN 'State' = 'State' THEN 'State 1','State 2','State 3'