2013-03-05 71 views
-2

考虑表“T1”分组:SQL查询来选择“名”以最小的“时间戳”,由“group_fk”

+------------------------------+ 
| timestamp | name | group_fk | 
+------------+------+----------+ 
| 1362297600 | abc | 41  | 
| 1362384000 | bcd | 41  | 
| 1362470400 | cde | 41  | 
| 1362556800 | def | 42  | 
| 1362643200 | efg | 42  | 
+------------------------------+ 

我需要选择“名”,在每个“最小的“时间戳” group_fk”。所以结果应该是:“abc”和“def”。

我知道丑陋的(而且并不总是正确的)的方式来做到这一点:

select name 
from t1 
where t1.timestamp IN (
    select min(t1_inner.timestamp) 
    from t1 t1_inner 
    group by t1_inner.group_fk 
) 

有没有更好的解决办法?

- DM

+0

“更好” 在何种意义上,到底是什么? – 2013-03-05 23:50:33

+0

哪些是dbms? – 2013-03-05 23:53:52

回答

2

这可以通过许多不同的方式,包括使用子查询:

select t1.name, t2.minval 
from table1 t1 
inner join 
(
    select min(timestamp) MinVal, 
    group_fk 
    from table1 
    group by group_fk 
) t2 
    on t1.timestamp = t2.minval 
    and t1.group_fk = t2.group_fk 

SQL Fiddle with Demo

或者,如果你的数据库窗口函数,你可以使用row_number()

select name, timestamp 
from 
(
    select name, timestamp, 
    row_number() over(partition by group_fk order by timestamp) rn 
    from table1 
) src 
where rn = 1 

SQL Fiddle with Demo