日期:2014-05-18 浏览次数:20576 次
id productname listdate 1 A 2011-01-02 2 B 2011-01-05 3 A 2010-02-03 4 C 2011-03-04 5 A 2011-04-05 6 B 2011-01-01
id productname listdate listdate1 1 A 2011-01-02 2010-02-03 2 B 2011-01-05 2011-01-01 3 A 2010-02-03 null 4 C 2011-03-04 null 5 A 2011-04-05 2011-01-02 6 B 2011-01-01 null
SELECT * , (select min(listdate) from #t B where a.productname = b.productname and b.listdate > a.listdate) as listdate1 FROM #t A
------解决方案--------------------
select n.id.miproductname,n.listdate,m.listdate1 from ( select id,productname,listdate listdate1 from test a where not exists(select 1 from test b where a.productname=b.productname and a.listdate <b.listdate ))t right join test n on ty.id=n.id
------解决方案--------------------
?LZ?最近一次的日期是按照什么排序的呢?
if object_id('[TB]') is not null drop table [TB] go create table [TB] (id int,productname nvarchar(2),listdate datetime) insert into [TB] select 1,'A','2011-01-02' union all select 2,'B','2011-01-05' union all select 3,'A','2010-02-03' union all select 4,'C','2011-03-04' union all select 5,'A','2011-04-05' union all select 6,'B','2011-01-01' select * from [TB] SELECT id , productname , listdate , ( SELECT TOP 1 listdate FROM TB WHERE productname = A.Productname AND listdate <> A.listdate AND id >A.id ORDER BY listdate asc ) AS listdate2 FROM dbo.TB A /* id productname listdate listdate2 ----------- ----------- ----------------------- ----------------------- 1 A 2011-01-02 00:00:00.000 2010-02-03 00:00:00.000 2 B 2011-01-05 00:00:00.000 2011-01-01 00:00:00.000 3 A 2010-02-03 00:00:00.000 2011-04-05 00:00:00.000 4 C 2011-03-04 00:00:00.000 NULL 5 A 2011-04-05 00:00:00.000 NULL 6 B 2011-01-01 00:00:00.000 NULL (6 row(s) affected) */
------解决方案--------------------