比对同表中不同天数,时间最大的数据。 表结构:
create table test
(
id int primary key identity(1,1),
brandid int,
name varchar(50),
[datetime] datetime
)
数据:
insert into test values(1,'第一个品牌14日第一条','2013-03-14 14:14:14')
insert into test values(1,'第一个品牌14日第二条','2013-03-14 15:14:14')
insert into test values(1,'第一个品牌15日第一条','2013-03-15 11:14:14')
insert into test values(1,'第一个品牌15日第二条','2013-03-15 12:14:14')
insert into test values(2,'第二个品牌14日第一条','2013-03-14 14:14:14')
insert into test values(2,'第二个品牌14日第二条','2013-03-14 15:14:14')
insert into test values(2,'第二个品牌15日第一条','2013-03-15 13:14:14')
insert into test values(2,'第二个品牌15日第二条','2013-03-15 16:14:14')
select t1.brandid,t1.name,t1.datetime,t2.brandid,t2.name,t2.datetime from test t1,test t2
where convert(varchar(10),dateadd(day,1, t1.[datetime]),120)=convert(varchar(10), t2.[datetime],120)
and not exists(select 1 from test t3 where convert(varchar(10), t1.[datetime],120)=convert(varchar(10), t3.[datetime],120) and t1.[datetime]<t3.[datetime])
and not exists(select 1 from test t3 where convert(varchar(10), t2.[datetime],120)=convert(varchar(10), t3.[datetime],120) and t2.[datetime]<t3.[datetime])
------解决方案--------------------
后面掉了个条件
select t1.brandid,t1.name,t1.datetime,t2.brandid,t2.name,t2.datetime from test t1,test t2
where convert(varchar(10),dateadd(day,1, t1.[datetime]),120)=convert(varchar(10), t2.[datetime],120)
and t1.brandid=t2.brandid
and not exists(select 1 from test t3 where convert(varchar(10), t1.[datetime],120)=convert(varchar(10), t3.[datetime],120) and t1.[datetime]<t3.[datetime] and t1.brandid=t3.brandid)
and not exists(select 1 from test t3 where convert(varchar(10), t2.[datetime],120)=convert(varchar(10), t3.[datetime],120) and t2.[datetime]<t3.[datetime] and t1.brandid=t3.brandid)
------解决方案--------------------
我勒个去,你不会加个条件啊
where convert(varchar(10), t2.[datetime],120)=convert(varchar(10),getdate(),120)