blog.itcode.devblog.itcode.dev

[Programmers / MySQL] Level 1 Sort by Multiple Criteria (59404)

The ANIMAL_INS table contains information about animals that entered the animal shelter. The ANIMAL_INS table structure is as follows, where ANIMAL_ID, ANIMAL_TYPE, DATETIME, INTAKE_CONDITION, NAME, and SEX_UPON_INTAKE represent the animal's ID, species, intake date, condition at intake, name, and sex/neuter status, respectively.

[Programmers / MySQL] Level 1 Sort by Multiple Criteria (59404)

The ANIMAL_INS table contains information about animals that entered the animal shelter. The ANIMAL_INS table structure is as follows, where ANIMAL_ID, ANIMAL_TYPE, DATETIME, INTAKE_CONDITION, NAME, and SEX_UPON_INTAKE represent the animal's ID, species, intake date, condition at intake, name, and sex/neuter status, respectively.
RWB0104
@RWBwritten at 2021-12-16 10:22:38
Programmers

시리즈 모아보기

Programmers

34 / 78
RankLanguage Used
Level 1

🖼️ MySQL

🔗 Sort by Multiple Criteria

The ANIMAL_INS table contains information about animals that entered the animal shelter. The ANIMAL_INS table structure is as follows, where ANIMAL_ID, ANIMAL_TYPE, DATETIME, INTAKE_CONDITION, NAME, and SEX_UPON_INTAKE represent the animal's ID, species, intake date, condition at intake, name, and sex/neuter status, respectively.

NAMETYPENULLABLE
ANIMAL_IDVARCHAR(N)FALSE
ANIMAL_TYPEVARCHAR(N)FALSE
DATETIMEDATETIMEFALSE
INTAKE_CONDITIONVARCHAR(N)FALSE
NAMEVARCHAR(N)TRUE
SEX_UPON_INTAKEVARCHAR(N)FALSE

Write a SQL statement that retrieves the ID, name, and intake date of every animal that entered the shelter, ordered by name. However, among animals with the same name, the one whose protection started later should be shown first.

For example, if the ANIMAL_INS table is as follows:

ANIMAL_IDANIMAL_TYPEDATETIMEINTAKE_CONDITIONNAMESEX_UPON_INTAKE
A349996Cat2018-01-22 14:32:00NormalSugarNeutered Male
A350276Cat2017-08-13 13:50:00NormalJewelSpayed Female
A396810Dog2016-08-22 16:13:00InjuredRavenSpayed Female
A410668Cat2015-11-19 13:41:00NormalRavenSpayed Female
  1. Sorting the names alphabetically gives 'Jewel', 'Raven', 'Sugar'.
  2. Since there is both a dog and a cat named 'Raven', the one whose protection started later (the dog) is shown first among them.

Therefore, running the SQL statement should produce the following result:

ANIMAL_IDNAMEDATETIME
A350276Jewel2017-08-13 13:50:00
A396810Raven2016-08-22 16:13:00
A410668Raven2015-11-19 13:41:00
A349996Sugar2018-01-22 14:32:00

Retrieve ANIMAL_ID, NAME, and DATETIME for all animals. Show the results in ascending order of NAME, but for animals with the same name, show the most recently admitted animal first — that is, in descending order of DATETIME.

SQL

SELECT ANIMAL_ID, NAME, DATETIME FROM ANIMAL_INS ORDER BY NAME, DATETIME DESC;
# Programmers# Algorithm# SQL# Level 1
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08