请教一个简单的sql语句

广州人 2011-09-09 04:27:42
id date name
1 2011-09-09 10:00:00 cxd
2 2011-09-08 10:00:00 cxd
3 2011-09-07 10:00:00 cxd
4 2011-09-08 10:00:00 yejin
5 2011-09-09 10:00:00 yejin
6 2011-09-10 10:00:00 yejin

我需要返回的数据是以CXD来分组,时间最早的一条
返回的结果是:
3 2011-09-07 10:00:00 cxd
4 2011-09-08 10:00:00 yejin

请教各位高手
...全文
100 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2011-09-10
  • 打赏
  • 举报
回复

select t.* from tb t where date = (select min(date) from tb where CXD = t.CXD) order by t.id
select t.* from tb t where not exists (select 1 from tb where CXD = t.CXD and date < t.date) order by t.id
--小F-- 2011-09-09
  • 打赏
  • 举报
回复
select * from tb t where date=(select max(date) from tb where name =t.name)
chuanzhang5687 2011-09-09
  • 打赏
  • 举报
回复
create table tb 
(
id int,
date datetime,
name varchar(10)
)
insert into tb values(1,'2011-09-09 10:00:00','cxd')
insert into tb values(2,'2011-09-08 10:00:00','cxd')
insert into tb values(3,'2011-09-07 10:00:00','cxd')
insert into tb values(4,'2011-09-08 10:00:00','yejin')
insert into tb values(5,'2011-09-09 10:00:00','yejin')
insert into tb values(6,'2011-09-10 10:00:00','yejin')

select id ,date , name from tb t
where not exists(select 1 from tb where t.name = name and t.date>date)
/*
id,date,name
3,2011-09-07 10:00:00.000,cxd
4,2011-09-08 10:00:00.000,yejin

(2 行受影响)
修改一下
水族杰纶 2011-09-09
  • 打赏
  • 举报
回复
;with tmp
as
(select rownum=row_number()over(partition by CXD order by [date]),
*
from tb)
select * from tmp
where rownum=1
areswang 2011-09-09
  • 打赏
  • 举报
回复
select * from tb t
where not exists(select 1 from tb where name=t.name and dt<t.dt)
广州人 2011-09-09
  • 打赏
  • 举报
回复
还要有编号也要返回出来
chuanzhang5687 2011-09-09
  • 打赏
  • 举报
回复
select id ,date , name from tb t
where not exists(select 1 from tb where t.id = id and t.date<date)
chuanzhang5687 2011-09-09
  • 打赏
  • 举报
回复
select min(date),name from tb group by name

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧