来自group by的前2个值

时间:2009-10-28 13:12:32

标签: mysql

当我按详细信息列分组并查找日期“2009-08-05”时,我也想要更早的一天ID。

select id,  details, abc_date from test order by details limit 10;
+------------+------------------+------------+
| id         | details          | abc_date   |
+------------+------------------+------------+
|       2224 | 10025            | 2009-08-11 | 
|       4575 | 10025            | 2009-09-02 | 
|       1617 | 10025            | 2009-08-05 | 
|       3614 | 10025            | 2009-08-24 | 
|       1811 | 10025            | 2009-08-07 | 
|        969 | 10025            | 2009-07-29 | 
|       1441 | 10025            | 2009-08-03 | 
|       4345 | 10025            | 2009-08-31 | 
|       3330 | 10025            | 2009-08-21 | 
|        799 | 10025            | 2009-07-27 | 
+------------+------------------+------------+

2 个答案:

答案 0 :(得分:1)

SELECT  details,
        (
        SELECT  id
        FROM    test ti
        WHERE   ti.details = to.details
        ORDER BY
                date
        LIMIT 1
        ) AS first_id
FROM    test to
GROUP BY
        details

答案 1 :(得分:0)

如果您的意思是在详细信息中按日期排序(并且从您的问题中不清楚这是您想要的),请尝试:

select id,  details, abc_date from test order by details,abc_date limit 10;