在一个sql命令访问中从一个数据库表中选择多个计数

时间:2013-06-27 18:15:27

标签: sql ms-access select

我有一个表格,格式如下:

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解决方案不起作用。谢谢你的任何建议。

2 个答案:

答案 0 :(得分:4)

看起来这可能是因为不使用表别名而导致的问题。因为您在外部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

答案 1 :(得分:2)

Aiias的回答解释了为什么您当前的查询无效,但我想我已经指出您不能使用CASE WHEN解决方案的假设只是部分正确,是的,您可以&# 39; t使用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;