27,579
社区成员
发帖
与我相关
我的任务
分享
if object_id('[t1]') is not null drop table [t1]
go
create table [t1]([AutoID] int,[SID] varchar(2),[STimes] int,[SDate] datetime)
insert [t1]
select 1,'s1',1,'2009-4-1' union all
select 2,'s2',1,'2009-4-1' union all
select 3,'s2',2,'2009-4-20' union all
select 4,'s3',1,'2009-4-1' union all
select 10,'s4',1,'2009-4-1' union all
select 11,'s4',2,'2009-4-10' union all
select 12,'s4',3,'2009-4-20'
go
--select * from [t1]
--1.
select * from t1 t
where SDate>'2009-3-20' and SDate <'2009-4-15'
and AutoID=(select top 1 AutoID from t1 where sid=t.sid order by SDate desc)
/*
AutoID SID STimes SDate
----------- ---- ----------- -----------------------
1 s1 1 2009-04-01 00:00:00.000
4 s3 1 2009-04-01 00:00:00.000
(2 行受影响)
*/
--2.
select * from t1 t
where SDate>'2009-3-20' and SDate <'2009-4-25'
and AutoID=(select top 1 AutoID from t1 where sid=t.sid order by SDate desc)
/*
AutoID SID STimes SDate
----------- ---- ----------- -----------------------
1 s1 1 2009-04-01 00:00:00.000
3 s2 2 2009-04-20 00:00:00.000
4 s3 1 2009-04-01 00:00:00.000
12 s4 3 2009-04-20 00:00:00.000
(4 行受影响)
*/
create table t1(AutoID int, SID varchar(5), STimes int, SDate datetime)
go
insert t1 select 1, 's1', 1, '2009-4-1'
insert t1 select 2 , 's2', 1, '2009-4-1'
insert t1 select 3 , 's2', 2, '2009-4-20'
insert t1 select 4, 's3', 1, '2009-4-1'
insert t1 select 10 ,'s4', 1 ,'2009-4-1'
insert t1 select 11 ,'s4' ,2, '2009-4-10'
insert t1 select 12 ,'s4' ,3 ,'2009-4-20'
go
select AutoID,SID,STimes, SDate=convert(varchar(10),SDate,120) from (
select * from t1 a where not exists(select 1 from t1 where sid=a.sid and STimes>a.STimes)) b where SDate>'2009-3-20' and SDate <'2009-4-15'
/*
AutoID SID STimes SDate
----------- ----- ----------- ----------
1 s1 1 2009-04-01
4 s3 1 2009-04-01
(所影响的行数为 2 行)
*/
go
select AutoID,SID,STimes, SDate=convert(varchar(10),SDate,120) from (
select * from t1 a where not exists(select 1 from t1 where sid=a.sid and STimes>a.STimes)) b where SDate>'2009-3-20' and SDate <'2009-4-25'
/*
AutoID SID STimes SDate
----------- ----- ----------- ----------
1 s1 1 2009-04-01
3 s2 2 2009-04-20
4 s3 1 2009-04-01
12 s4 3 2009-04-20
(所影响的行数为 4 行)
*/
go
drop table t1
select * from (
select * from t1 a where not exists(select 1 from t1 where sid=a.sid and STimes>a.STimes)) b where SDate>'2009-3-20' and SDate <'2009-4-25'
select * from (
select * from t1 a where not exists(select 1 from t1 where sid=a.sid and STimes>a.STimes)) b where SDate>'2009-3-20' and SDate <'2009-4-15'
select *
from tb T1
where not exists (select 1 from tb T2 wher T1.s1=T2.s1 and T1.sdate<t2.sdate)
and sid not in
(
select sid
from tb
group by sid
where sdate between @date1 and @date2
)