in reply to Sorting and Grouping with two different fields

Let's see if I've got this right... You want to sort the data such that all the records for each state are together and the states should be ordered based on the lowest id present for each state, correct?

SQL can do that.

SELECT * FROM states; id | state | city ----+------------+---------------- 1 | Virginia | Norfolk 2 | Virginia | Chesapeake 3 | Virginia | Virginia Beach 4 | Indiana | Evansville 5 | Indiana | Fort Wayne 6 | Virginia | Falls Church 7 | Indiana | Indianapolis 8 | Washington | Seatle 9 | Washington | Spokane SELECT s.id AS id, s.state AS state, s.city AS city FROM states s JOIN + (SELECT min(id) AS min_id, state FROM states GROUP BY state) j ON s. +state = j.state ORDER BY j.min_id, s.id ; id | state | city ----+------------+---------------- 1 | Virginia | Norfolk 2 | Virginia | Chesapeake 3 | Virginia | Virginia Beach 6 | Virginia | Falls Church 4 | Indiana | Evansville 5 | Indiana | Fort Wayne 7 | Indiana | Indianapolis 8 | Washington | Seatle 9 | Washington | Spokane
(Tested using PostgreSQL. Your syntax may vary.)

Replies are listed 'Best First'.
Re^2: Sorting and Grouping with two different fields
by atemon (Chaplain) on Jul 12, 2007 at 15:48 UTC

    Thanks for the SQL solution. It works with MySQL 5.0.x also. Thanks a lot.

    --VC