5

我有一个格式如下的表:

STATE SURVEY_ANSWER  
NC high  
NC moderate  
WA high  
FL low  
NC high

我正在寻找一个可以得到以下结果的查询:

STATE HIGH MODERATE LOW 
NC 2 1 0  
WA 1 0 0  
FL 0 0 1

不幸的是,这些是我得到的结果:

STATE HIGH MODERATE LOW 
NC 3 1 1  
WA 3 1 1  
FL 3 1 1  

这是我正在使用的代码:

Select mytable.STATE,
(SELECT COUNT(*) FROM mytable WHERE mytable.survey_answer = 'low' and state = mytable.state) AS low,
(SELECT COUNT(*) FROM mytable WHERE mytable.survey_answer = 'moderate' and state = mytable.state) AS moderate,
(SELECT COUNT(*) FROM mytable WHERE mytable.survey_answer = 'high' and state = mytable.state) AS high,
FROM mytable
GROUP BY mytable.state;

虽然这个论坛和其他论坛非常有帮助,但我无法弄清楚我做错了什么。请注意:我使用的是 Access,因此 CASE WHEN 解决方案不起作用。谢谢你的任何建议。

4

2 回答 2

5

看起来这可能是由于不使用表别名引起的问题。因为您在外部正在使用的同一个表上执行子查询SELECT并且没有给外部表一个别名,所以子查询中的两个条件WHERE都只使用子查询中的数据。

换句话说,当你写:

SELECT COUNT(*) FROM mytable WHERE mytable.survey_answer = 'low' and state = mytable.state

它对外部查询一无所知。

尝试这个:

SELECT t1.STATE,
  (SELECT COUNT(*) FROM mytable t2 WHERE t2.state = t1.state AND t2.survey_answer = 'low') low,
  (SELECT COUNT(*) FROM mytable t3 WHERE t3.state = t1.state AND t3.survey_answer = 'moderate') moderate,
  (SELECT COUNT(*) FROM mytable t4 WHERE t4.state = t1.state AND t4.survey_answer = 'high') high,
FROM mytable t1
GROUP BY t1.state
于 2013-06-27T18:20:39.667 回答
2

Aiias 回答解释了为什么您当前的查询不起作用,但我想我会指出您不能使用CASE WHEN解决方案的假设只是部分正确,是的,您不能使用CASE WHEN,但这并不意味着您需要相关的子查询. 你可以简单地使用:

SELECT  mytable.STATE,
        SUM(IIF(mytable.survey_answer = 'low', 1, 0) AS low,
        SUM(IIF(mytable.survey_answer = 'moderate', 1, 0) AS moderate,
        SUM(IIF(mytable.survey_answer = 'high', 1, 0) AS high
FROM    mytable
GROUP BY mytable.state;
于 2013-06-27T18:46:35.287 回答