我有一个表tblSchedule,以下是其中的值。
INSERT INTO tblSchedule (`scheduleID`, `eventID`, `price`, `eventDate`) VALUES
(1, 1, 150, '2013-04-20 00:00:00'),
(2, 1, 100, '2013-04-15 00:00:00'),
(3, 2, 80, '2013-04-18 00:00:00'),
(4, 3, 120, '2013-04-26 00:00:00'),
(5, 3, 140, '2013-04-22 00:00:00'),
(6, 2, 100, '2013-04-22 00:00:00');
我想获得eventDate ASC订购的Unique事件。
我尝试过以下查询,但这会给出错误的价格值和正确的eventDates。
SELECT MIN(eventDate) as minEventDate, eventId, price
FROM tblSchedule
GROUP BY eventID
ORDER BY minEventDate
Click Here to see code in action
有人能告诉我这里发生了什么以及正确查询的细分吗?
答案 0 :(得分:3)
首先,您应该为每个MIN(EventDate)
找到eventID
,然后使用JOIN
eventID
和MIN(EventDate)
的原始表格中的行
SELECT * FROM tblSchedule
JOIN
( SELECT MIN(eventDate) as minEventDate,
eventId
FROM tblSchedule
GROUP BY eventID
) as T on tblSchedule.eventID=t.EventId
AND
tblSchedule.eventDate=t.minEventDate
ORDER BY eventDate
答案 1 :(得分:1)
试试这个:
SELECT eventDate, eventId, price
FROM (SELECT eventDate, eventId, price
FROM tblSchedule
ORDER BY eventId, eventDate
) AS A
GROUP BY eventId;
<强>输出强>
| EVENTDATE | EVENTID | PRICE |
|------------------------------|---------|-------|
| April, 15 2013 00:00:00+0000 | 1 | 100 |
| April, 18 2013 00:00:00+0000 | 2 | 80 |
| April, 22 2013 00:00:00+0000 | 3 | 140 |
答案 2 :(得分:0)
您可以为此
使用时间戳SELECT * FROM `tblschedule` ORDER BY TIMESTAMP( eventDate )
OR
SELECT DISTINCT(eventID) as event, eventDate FROM `tblschedule` ORDER BY TIMESTAMP( eventDate )
而不是*你可以放置你想要返回的任何列。