I have a SQL query ending with:
...
ORDER BY event_date ASC
So that I get these results:
|-------------------------------------|
| location_id | event_date | event_id |
|-------------------------------------|
| 112 | 2014-06-01 | 501 |
|-------------------------------------|
| 19 | 2014-06-04 | 508 |
|-------------------------------------|
| 112 | 2014-06-17 | 667 |
|-------------------------------------|
| 19 | 2014-07-07 | 434 |
|-------------------------------------|
I was wondering if I can use a different ORDER BY
clause to get the following results:
|-------------------------------------|
| location_id | event_date | event_id |
|-------------------------------------|
| 112 | 2014-06-01 | 501 |
|-------------------------------------|
| 112 | 2014-06-17 | 667 |
|-------------------------------------|
| 19 | 2014-06-04 | 508 |
|-------------------------------------|
| 19 | 2014-07-07 | 434 |
|-------------------------------------|
EDIT:
In other words, I want the earliest event_date
(with location_id
= X), and then all the other rows with location_id
= X, ordered by event_date
.
Then the next earliest event_date
(with location_id
!= X = Y), and again all the rows with location_id
= Y, ordered by event_date
.
And so on...
You can join onto a derived table that calculates the first event_date for each location and use that for ordering.
SELECT E1.*
FROM Events E1
JOIN (SELECT location_id,
MIN(event_date) AS min_date
FROM Events
GROUP BY location_id) AS E2
ON E1.location_id = E2.location_id
ORDER BY E2.min_date,
E1.location_id, -- In case two locations have same MIN(event_date)
E1.event_date
您应该使用此ORDER BY子句获取所需的结果:
ORDER BY location_id DESC, event_date 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.