如何使用GROUP BY得到第一条记录呢?

时间:2021-05-04 00:26:26
表:
主叫号码  被叫号码  主叫发起时间 
123456    456789     2007-04-02 16:00:00
654321    111111     2007-04-02 17:00:00
123456    222222     2007-04-02 17:00:00
123456    333333     2007-04-02 18:00:00

我的目的,要得到主叫号码第一次发起的那条记录呢?
我如何使用SQL语句实现呢?
结果
主叫号码  被叫号码  主叫发起时间 
123456    456789     2007-04-02 16:00:00
654321    111111     2007-04-02 17:00:00

5 个解决方案

#1


SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select top 1 主叫发起时间 from 表名 where 主叫号码=T.主叫号码)

#2


不一定是TOP 1,是“主叫发起时间”最早的那条记录。

#3


SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select min(主叫发起时间) from 表名 where 主叫号码=T.主叫号码)

#4


SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select min(主叫发起时间) from 表名 where 主叫号码=T.主叫号码)


--或,取 主叫发起时间 升序排列的第一条

SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select top 1 主叫发起时间 from 表名 where 主叫号码=T.主叫号码 order by 主叫发起时间 )

#5


必须要有唯一标识的字段,如是时间的话,上述代码即可,否则增加
自增字段

#1


SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select top 1 主叫发起时间 from 表名 where 主叫号码=T.主叫号码)

#2


不一定是TOP 1,是“主叫发起时间”最早的那条记录。

#3


SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select min(主叫发起时间) from 表名 where 主叫号码=T.主叫号码)

#4


SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select min(主叫发起时间) from 表名 where 主叫号码=T.主叫号码)


--或,取 主叫发起时间 升序排列的第一条

SELECT T.*
FROM 表名 AS T
where 主叫发起时间=(select top 1 主叫发起时间 from 表名 where 主叫号码=T.主叫号码 order by 主叫发起时间 )

#5


必须要有唯一标识的字段,如是时间的话,上述代码即可,否则增加
自增字段