我的SQL查询以:
结尾...
ORDER BY event_date ASC
所以我得到了这些结果:
|-------------------------------------|
| 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 |
|-------------------------------------|
我想知道我是否可以使用不同的ORDER BY
子句来获得以下结果:
|-------------------------------------|
| 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 |
|-------------------------------------|
编辑:
换句话说,我想要最早的event_date
(location_id
= X),然后是location_id
= X的所有其他行,按event_date
排序。
然后是下一个最早的event_date
(location_id
!= X = Y),以及location_id
= Y的所有行,按event_date
排序。
等等...
答案 0 :(得分:1)
您可以加入一个派生表,该表计算每个位置的第一个event_date并将其用于排序。
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
答案 1 :(得分:0)
您应该使用此ORDER BY子句来获得所需的结果:
ORDER BY location_id DESC, event_date ASC