关于取出最近一次日期的sql语句

fstao 2012-05-17 03:48:49
比如表#t数据如下:

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



我想取出在#t.productname有相同时,在listdate1里显示出最近一次日期,如下:

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

如何写sql语句?
...全文
1153 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
fstao 2012-05-17
  • 打赏
  • 举报
回复
应该是这样写才对,根据上面的语句改了一下:

SELECT * ,
(select max(listdate) from #t B where a.productname = b.productname
and b.listdate < a.listdate) as listdate1

FROM #t A

anzhiqiang_touzi 2012-05-17
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
SQL code

SELECT * ,
(select min(listdate) from #t B where a.productname = b.productname
and b.listdate > a.listdate) as listdate1

FROM #t A
[/Quote]
Mr_Nice 2012-05-17
  • 打赏
  • 举报
回复

?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)
*/
  • 打赏
  • 举报
回复

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
Mr_Nice 2012-05-17
  • 打赏
  • 举报
回复
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 --这里不是2011-04-05?
4 C 2011-03-04 null
5 A 2011-04-05 2011-01-02
6 B 2011-01-01 null
天-笑 2012-05-17
  • 打赏
  • 举报
回复

SELECT * ,
(select min(listdate) from #t B where a.productname = b.productname
and b.listdate > a.listdate) as listdate1

FROM #t A


34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧