简体   繁体   中英

mySQL select maximum value for column A with same values in column B

Here's the table in question, generated from the command at the bottom of this question:

+--------------+-----------------+
| 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 |
+--------------+-----------------+

I'd like to find the largest value in the second column for each value in column one, so the output would be something like:

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

the two columns are from different tables so at the moment this is my command:

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;

GROUP BY should help:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM