2012-05-03 40 views
0

我正在用这个SQL查询绝对脑细分,我希望有人可以照亮我应该做的一些事情。如何使用group by子句从MS Access表中获取计数?

我有以下表格,它们通过“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 | 

只是不知道如何让每一个计数。我试过数(不同的),但Access不喜欢它。

只要我在它的使用计数,如:

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

回答

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

没有尝试过这一点,但在这里不用。你需要使用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 
+0

感谢您的。刚更新的问题与如果我尝试使用计数会发生什么。 – Menztrual

+0

您还需要拥有一个群组。请通过a添加组。acountry,r.result_placing到您的查询结束 –

1

下面是使用LEFT OUTER JOINGROUP 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