SQL查询选择“name”,最小“timestamp”按“group_fk”分组

时间:2013-03-05 23:49:46

标签: sql

考虑表“t1”:

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

我需要在每个“group_fk”中选择最少“timestamp”的“name”。所以结果应该是:“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

1 个答案:

答案 0 :(得分:3)

这可以通过多种方式完成,包括使用子查询:

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