34,590
社区成员
发帖
与我相关
我的任务
分享
select a.*,MAX(b.createtime) 最后回复时间 from #temp a,#temp b where a.parentid=0 and a.id = b.parentid
group by a.id,a.createtime,a.name,a.parentid
order by 最后回复时间 desc
create table #temp (
id int null,
name nvarchar(10) null,
createtime datetime null,
parentid int null
)
insert into #temp
select 1,'aaa','2009-08-08',0 union all select
2, 'bbb' ,'2009-08-08', 0 union all select
3, 'ccc' ,'2009-08-08', 0 union all select
4, 'ddd' ,'2009-08-09', 1 union all select
5, 'eee' ,'2009-08-29', 2 union all select
6, 'fff' ,'2009-08-19', 1 union all select
7, 'ggg' ,'2009-08-09',2
select *,(select MAX(createtime) from #temp where parentid = a.id) 最后回复时间 from #temp a
where exists(select 1 from #temp where parentid = a.id)
order by 最后回复时间 desc
---------------------------------
--2 bbb 2009-08-08 00:00:00.000 0 2009-08-29 00:00:00.000
--1 aaa 2009-08-08 00:00:00.000 0 2009-08-19 00:00:00.000