日期:2014-05-17  浏览次数:20472 次

比对同表中不同天数,时间最大的数据。
表结构:
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')

想要查询出的效果:
1 第一个品牌14日第二条 2013-03-14 15:14:14.000 1 第一个品牌15日第二条 2013-03-15 12:14:14.000
2 第二个品牌14日第二条 2013-03-14 15:14:14.000 2 第二个品牌15日第二条 2013-03-15 16:14:14.000

现在可以并行显示,但是都很混乱,不是自己想要的结果,求教高手

------解决方案--------------------
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])

------解决方案--------------------
引用:
引用:SQL code?1234select 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)=conve……

后面掉了个条件
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)