简体   繁体   中英

How to group by columns twice in MYSQL

I have a database with a table that looks like this with these fields . I want to return the first_name and surnames of all the pupils and group them by pupil_group, and then by year, and order the groups by alphabetical DESC (pupil_group), ASC (year) and then alphabetical DESC (surname).

For example, running SELECT * FROM pupils; on the table above should return this:

(((('Jonathan', 'Morris'))), ((('Amber', 'Wilfred))), ((('Grace' ,'Harlow'))), ((('Elizabeth', 'Van Stephen'))), ((('Craig', 'Filip'))), ((('Alice', 'Howard'))), ((('Christopher', 'Paulsen'))), ((('William', 'Chong')), (('Matthew', 'Chong'))), ((('Jessica', 'Harris'))))

So it is in this format: the outer brackets define the collective pupils, the brackets within that define the pupil_groups, the brackets with that define the years, then the brackets within that define the individual pupils.

Sorry if this is not very clear of if I have made a mistake. If there is anything I can clarify to make this easier to understand then let me know and I will do so.

Currently I have tried SELECT first_name, surname from pupils GROUP BY pupil_group, year ORDER BY pupil_group, year ASC but it's not merging them into groups or ordering them how I would like.

Thanks.

EDIT: I've just realised my year column is a varchar(2) and so maybe it can't be sorted since it contains numbers. I think I'll make that an int instead.

EDIT2: I updated year to be int . I have now tried SELECT first_name, surname, year, pupil_group FROM pupils ORDER BY pupil_group ASC, year ASC, surname ASC as suggested below (added year and pupil_group to make it easier to interpret), but this returns (('Jonathan', 'Morris', 9, 'Apollo'), ('Amber', 'Wilfred', 9, 'Artemis'), ('Grace', 'Harlow', 9, 'Athena'), ('Elizabeth', 'Van Stephen', 9, 'Demeter'), ('Jessica', 'Harris', 10, 'Demeter'), ('Craig', 'Filip', 9, 'Hades'), ('Alice', 'Howard', 9, 'Hera'), ('Christopher', 'Paulsen', 9, 'Hermes'), ('William', 'Chong', 9, 'Poseidon'), ('Matthew', 'Chong', 10, 'Poseidon')) . While it does order them correctly, none of them are grouped as I have described.

I think you just are having difficult articulating an ORDER BY clause:

SELECT First_Name, Surname, Pupil_Group, Year
FROM pupils
ORDER BY pupil_group DESC, year, Surname DESC;

This would place all records in the same pupil group together. Then, within each such group, the records would be sorted ascending by the year, followed by descending by the last name.

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