2012-05-03 42 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