日期:2014-05-18  浏览次数:20498 次

sql简单查询
表tab 字段如下
id,name datetime
1 张三 2012-01-02 09:21:21
2 张三 2012-01-02 23:23:23
3 张四 2012-01-03 09:21:21

查出 根据name分组,如果name内容有重复的就取datetime时间最小的那个
结果如下

1 张三 2012-01-02 09:21:21
3 张四 2012-01-03 09:21:21
谢谢各位!!!!

------解决方案--------------------
SQL code

create table Test
(ID int identity (1,1),UserName varchar(10),Times datetime)

insert into Test values('张三','2012-01-02 09:21:21')
insert into Test values('张三','2012-01-02 23:23:23')
insert into Test values('张四','2012-01-03 09:21:21')

select UserName,Min(Times) from Test group by UserName

------解决方案--------------------
select id,name,[datetime] from
(select *,row_number() over(partition by name order by [datetime]) as rownum
from tab) as tb1
where rownum<2