22,207
社区成员
发帖
与我相关
我的任务
分享
create table tb
(
id int
,date datetime
,dvalue int
)
go
insert into tb
select 1,'2011-12-30 19:29:00',1
union all select 1,'2011-12-30 19:36:00',1
union all select 1,'2011-12-30 20:00:00',1
union all select 2,'2011-12-30 20:29:00',3
union all select 2,'2011-12-30 20:31:00',2
union all select 3,'2011-12-30 21:00:00',5
union all select 4,'2011-12-30 22:00:00',6
union all select 5,'2011-12-30 23:00:00',7
这里需要精确到分钟,取分钟最大值;
/*-------显示结果-------
1,'2011-12-30 19:36:00',1
1,'2011-12-30 20:00:00',1
2,'2011-12-30 20:31:00',2
3,'2011-12-30 21:00:00',5
4,'2011-12-30 22:00:00',6
5,'2011-12-30 23:00:00',7
*/
create table tb
(
id int
,date datetime
,dvalue int
)
go
insert into tb
select 1,'2011-12-30 19:29:00',1
union all select 1,'2011-12-30 19:36:00',1
union all select 1,'2011-12-30 20:00:00',1
union all select 2,'2011-12-30 20:29:00',3
union all select 2,'2011-12-30 20:31:00',2
union all select 3,'2011-12-30 21:00:00',5
union all select 4,'2011-12-30 22:00:00',6
union all select 5,'2011-12-30 23:00:00',7
go
select t.* from tb t where not exists(select 1 from tb where id = t.id and date > t.date) order by t.id
/*
id date dvalue
----------- ------------------------------------------------------ -----------
1 2011-12-30 20:00:00.000 1
2 2011-12-30 20:31:00.000 2
3 2011-12-30 21:00:00.000 5
4 2011-12-30 22:00:00.000 6
5 2011-12-30 23:00:00.000 7
(所影响的行数为 5 行)
*/
select t.* from tb t where date = (select max(date) from tb where id = t.id) order by t.id
/*
id date dvalue
----------- ------------------------------------------------------ -----------
1 2011-12-30 20:00:00.000 1
2 2011-12-30 20:31:00.000 2
3 2011-12-30 21:00:00.000 5
4 2011-12-30 22:00:00.000 6
5 2011-12-30 23:00:00.000 7
(所影响的行数为 5 行)
*/
drop table tb
select * from tb t where not exists (select 1 from tb where id=t.id and datediff(hour,date,t.date)=0 and date>t.date)