mysql获取组数据的第一行和最后一行

时间:2012-02-18 15:50:18

标签: mysql group-by

我有一个事件表,

| id | title  | date       |
| 1  | party  | 2011-02-02 |
| 2  | party  | 2011-02-03 |
| 3  | party  | 2011-02-04 |
| 4  | party  | 2011-02-05 |
| 5  | brunch | 2011-05-20 |
| 6  | brunch | 2011-05-21 |
| 7  | brunch | 2011-05-22 |
| 8  | brunch | 2011-05-23 |

我想传输此结构的数据

| id | title  | start      | finish     |
| 1  | party  | 2011-02-02 | 2011-02-05 |
| 2  | brunch | 2011-05-20 | 2011-05-23 |

最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

没有新ID:

SELECT title, MIN(date) AS start, MAX(date) AS finish 
FROM event
GROUP BY title

要生成新ID,请使用计数器:

SET @counter = 0; 
SELECT ((@counter := (@counter+1))) AS id, title, MIN(date) AS start, MAX(date) AS finish     
FROM event
GROUP BY title