2013-02-13 87 views
0

這裏是有問題的表格,在這個問題從底部的命令生成:MySQL的選擇與B列中的值相同列的最大值

+--------------+-----------------+ 
| usr_postcode | pdp_point_total | 
+--------------+-----------------+ 
| MS2 8LA  |    160 | 
| MS2 8LA  |    140 | 
| MS2 8LA  |    110 | 
| MS2 8LA  |    100 | 
| MS2 8LA  |    90 | 
| MS2 8LA  |    80 | 
| MS2 8LA  |    50 | 
| MS2 8LA  |    30 | 
| WN4 9NV  |    25 | 
| MS2 8LA  |    20 | 
| SL6 1SR  |    10 | 
| SL1 4DX  |    10 | 
+--------------+-----------------+ 

我想找到的最大價值在一列各值的第二列,所以輸出會是這樣的:

------------- 
MS2 8LA | 160 
WN4 9NV | 25 
SL6 1SR | 10 
SL1 4DX | 10 
------------- 

兩列來自不同的表,這樣的時刻,這是我的命令:

SELECT DISTINCT users.usr_postcode, point_date_pairs.pdp_point_total FROM users 
INNER JOIN point_date_pairs ON users.usr_id_pk = point_date_pairs.usr_id_fk 
ORDER BY point_date_pairs.pdp_point_total DESC; 

回答

1

GROUP BY應該有所幫助:

SELECT users.usr_postcode, MAX(point_date_pairs.pdp_point_total) 
FROM users 
INNER JOIN point_date_pairs ON users.usr_id_pk = point_date_pairs.usr_id_fk 
GROUP BY users.usr_postcode ASC 
+0

是的,完美的作品,謝謝!沒有MAX()函數,它只是找到第一個匹配的pdp_point_total記錄並顯示它? – Odyssey 2013-02-13 19:23:50

+0

我不確定那裏有什麼行爲,但我不會依賴它,因爲行的順序可能會改變。如果您使用group,則應始終使用相應的聚合函數:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html – Nils 2013-02-13 22:00:32

相關問題