2013-04-25 55 views
-4

其實數學似乎沒有加起來。SQL查詢加入一個計數並從另一個表的平均值

這裏是我正在使用的查詢和我試圖訪問的2表(所有真實數據)。

SQL中的這個查詢拉Steve Smith有27個總數和27個計數amount。它應該是17.在相同的查詢中,它顯示John Smith有4個總數和2個計數amount

SELECT 
user.*, 
IFNULL(SUM(collection.amount), 0) AS usertotal, 
COUNT(collection.amount) AS userunique 
FROM user 
LEFT JOIN collection 
ON user.id = collection.userid 
GROUP BY collection.amount` 

表1(名爲user):

id | firstname | lastname | username | email 
1 | Steve  | Smith | SteveS | [email protected] 
2 | John  | Smith | JohnSmith| [email protected] 

表2(名爲collection):

id|userid|carid |amount 
1 1 74 1 
10 2 130 1 
11 2 48 1 
12 2 414 1 
13 2 415 1 
14 2 66 1 
15 2 404 1 
16 2 57 2 
17 2 331 1 
18 2 264 1 
19 2 325 1 
20 2 51 2 
21 2 185 1 
24 1 168 1 
25 1 11 1 
26 1 315 1 
27 1 51 1 
28 1 210 1 
29 1 433 1 
30 1 434 1 
31 1 460 1 
32 1 75 1 
33 1 238 1 
34 1 226 1 
35 1 396 1 
36 1 174 1 
37 1 12 1 
38 1 328 1 
39 1 4 1 



id| UN | Amount 
1 | 4 | 457 
2 | 4 | 28 
3 | 2 | 234 
4 | 1 | 235 
5 | 2 | 1 

我需要一個查詢來獲取用戶名的完整列表,以及user.id和collection之間的內連接(與總數和數量列相關).UN

我不知道SQL查詢,不知道爲什麼我的生活。幫幫我?

感謝,

回答

5
SELECT 
    user.UN as username, 
    IFNULL(SUM(collection.Amount), 0) AS sum, 
    COUNT(collection.Amount) AS count 
FROM user 
LEFT JOIN collection 
    ON user.id = collection.UN 
GROUP BY user.id 

你說你想用INNER JOIN,但不會顯示誰沒有在收藏表中記錄的用戶。因此,我使用了LEFT JOIN,以便返回整個用戶列表,如果他們沒有任何用戶,其金額的COUNTSUM將爲0。

+0

這解決它完美的我。萬分感謝! – Andrew 2013-04-25 05:48:02

+0

數學實際上並不加起來。我會更新我的原始文章並解釋。 – Andrew 2013-04-25 08:32:18

+0

「SUM」工作正常嗎?而對於'COUNT'的問題,我猜這是因爲它也計算了空值。我現在要解決一個問題。 – 2013-04-25 11:48:36

0

使用此:

select u.* , c.total_amount from users as u 
inner join (select un, sum(amount) total_amount 
from collection group by un) c on u.id = c.un 

PHP查詢:

$q = "select u.* , c.total_amount from users as u 
inner join (select un, sum(amount) total_amount 
from collection group by un) c on u.id = c.un";  
    $result = $this->db->query($q); 
    //echo $this->db->last_query(); 
+0

我認爲它應該讀取「on user.id = collection.UN」而不是「user.id = collection.id」。 – 2013-04-25 05:39:08

+0

它應該我相信,但即使我改變了上面的代碼,我得到:'在'子句''未知列'c.userid' – Andrew 2013-04-25 05:42:25

+0

@veekay在查詢中使用別名。好吧,有一件事是用用戶(表1名稱)和c用集合(表2名稱)代替u並檢查結果。 – 2013-04-25 05:54:42

相關問題