MySQL returning lowest zip code
-
08-01-2021 - |
Question
Got this SQL:
SELECT DISTINCT(LocCity), LocZipCode FROM exp_course_events order by LocCity
and this data:
INSERT INTO `exp_course_events` (`LocCity`, `LocZipCode`) VALUES
('Aguadilla', '00602'), ('Akron', '44300'),('Akron', '44333'),
('Albany', '12205'), ('Albuquerque', '87102'),
('Albuquerque', '87109'), ('Austin', '78741'),
('Austin', '78753'), ('Austin', '78757'),
('Bend', '97701'), ('San Antonio', '78200'),
('San Antonio', '78201'),
....
('San Antonio', '78207');
Need to return only one value for LocZipCode for each LocCity, prefereable the lowest number LocZipCode for that LocCity.
This is results I'd like:
Aguadilla, 00602
Akron, 44300
Albany, 12205
Albuquerque, 87102
Austin, 78741
Bend, 97701
San Antonio, 78200
San Diego, 92108
San Francisco, 94111
San Juan, 00926
Santa Clara (San Jose), 95054
Springdale, 72762
Springfield, 62703
St. Louis. 63105
Visalia, 993291
Waco, 76705
Warwick, 02886
Waukesha, 53186
West Chester, 45069
West Des Moines, 50300
Solution
SELECT LocCity, MIN(LocZipCode)
FROM exp_course_events
GROUP BY LocCity
ORDER BY LocCity
Read about the GROUP BY clause here.
OTHER TIPS
select LocCity, min(LocZipCode)
from exp_course_events
group by LocCity
A simple GROUP BY
with a MIN()
aggregate will do it. Just be sure to alias the MIN()
column with a name (like AS LocZipCode
) so you can fetch it more easily application-side.
SELECT LocCity, MIN(LocZipCode) AS LocZipCode FROM exp_course_events GROUP BY LocCity;
SELECT LocCity
, MIN(LocZipCode)
FROM exp_course_events
GROUP by LocCity
order by LocCity
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow