如何使用group by子句从MS Access表中获取计数?

时间:2012-05-03 02:11:01

标签: sql ms-access

我正在使用这个SQL查询进行绝对的大脑细分,我希望有人可以对我应该做的事情发表一些看法。

我有以下表格,它们由“anumber”链接;

athletes
--------
anumber     (id)
acountry    ('Australia','Japan')
aname

result_placing
--------------
result_id       id
anumber         (id linked to athletes)
result_placing  (Gold, Silver or null)

我想获得一份有多少金,银结果相关的国家名单。输出如:

country     | resul_placing | result_count
----------- | ------------- | ------------
Australia   | Gold          |       2
Australia   | Silver        |       1

我试过这样的事情:

SELECT      acountry 
FROM        athletes 
INNER JOIN  result_placing 
ON          athletes.anumber = result_placing.anumber

显示

 Australia | Gold   |
 Australia | Silver |

只是不确定如何获得每个的计数。我尝试过count(不同)但是Access不喜欢它。

我在其中使用Count就像:

SELECT      a.acountry
        ,   r.placing
        ,   count(a.acountry) 
FROM        athlete         a 
INNER JOIN  result_place    r 
ON          a.anumber       = r.anumber

我收到:

You tried to execute a query that does not include the specified expression 'acountry' as part of an aggregate function

3 个答案:

答案 0 :(得分:2)

尝试

SELECT      a.acountry
        ,   r.result_placing
        ,   sum(*) as cnt 
FROM        athletes        a 
RIGHT JOIN  result_placing  r 
ON          a.anumber       = r.anumber 
GROUP BY    a.acountry
        ,   r.result_placing 
ORDER BY    a.acountry

答案 1 :(得分:1)

没有试过这个,但是这里有。你需要使用group by。请尝试以下查询

SELECT a.acountry, r.result_placing, count(a.acountry) FROM athletes a INNER JOIN     result_placing r ON a.anumber = r.anumber group by a.acountry, r.result_placing

答案 2 :(得分:1)

以下是使用 LEFT OUTER JOIN GROUP BY 查询数据的一种方法。

Script

SELECT              a.acountry
                ,   IIf(r.result_placing = '' 
                        OR IsNull(r.result_placing), 
                        'n/a', 
                        r.result_placing
                    ) AS medal
                ,   COUNT(r.result_id) AS medalcount
FROM                athletes a
LEFT OUTER JOIN     result_placing r
ON                  a.anumber = r.anumber
GROUP BY            a.acountry
                ,   r.result_placing

Table Data

运动员表数据

athletes

results_placing 表数据

results_placings

Output

查询输出

query