sql小问题!

Small__Wolf 2009-09-07 05:04:41
表 bbscard

id name createtime parentid
1 aaa 2009-08-08 0
2 bbb 2009-08-08 0
3 ccc 2009-08-08 0
4 ddd 2009-08-09 1
5 eee 2009-08-29 2
6 fff 2009-08-19 1
7 ggg 2009-08-09 2

求一条sql语句,要求显示 按最新回复时间排序显示,正确结果如下

id name createtime parentid
1 bbb 2009-08-08 0
2 aaa 2009-08-08 0

...全文
69 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
ithhh2010 2009-09-07
  • 打赏
  • 举报
回复
create table bbscard(id int, name varchar(10), createtime datetime, parentid varchar(10) )


insert into bbscard 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 * from bbscard order by createtime desc

翼帆 2009-09-07
  • 打赏
  • 举报
回复
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


这样也成。
翼帆 2009-09-07
  • 打赏
  • 举报
回复
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
ivws_19 2009-09-07
  • 打赏
  • 举报
回复
select distinct t.* from bbscard t, bbscard t1 where t.parentid=0 and t.id=t1.parentid order by t1.createtime
ivws_19 2009-09-07
  • 打赏
  • 举报
回复
楼主是要把有回复的(这里只有前两条记录有回复)按回复日期排序显示出来
oflying907 2009-09-07
  • 打赏
  • 举报
回复
select * from 表 where parentid=0 order by createtime desc
这样?
--小F-- 2009-09-07
  • 打赏
  • 举报
回复
那答案也不止2条啊 应该是3条
soft_wsx 2009-09-07
  • 打赏
  • 举报
回复
如果是2005以前版本可以使用ROW——NUMBER()
小宏 2009-09-07
  • 打赏
  • 举报
回复
你说的和你想要显示的不明白
Small__Wolf 2009-09-07
  • 打赏
  • 举报
回复
表 bbscard

id name createtime parentid
1 aaa 2009-08-08 0
2 bbb 2009-08-08 0
3 ccc 2009-08-08 0
4 ddd 2009-08-09 1
5 eee 2009-08-29 2
6 fff 2009-08-19 1
7 ggg 2009-08-09 2


其中
4 ddd 2009-08-09 1
5 eee 2009-08-29 2
6 fff 2009-08-19 1
7 ggg 2009-08-09 2
是回复ID 1,2的信息
要求查询出信息的时候只显示pid为0的记录,并且按照回复时间最新的排序
fenlin 2009-09-07
  • 打赏
  • 举报
回复
没看明白楼主想要什么结果
华夏小卒 2009-09-07
  • 打赏
  • 举报
回复
什么规律
soft_wsx 2009-09-07
  • 打赏
  • 举报
回复
去重复处理!用EXISTS

34,590

社区成员

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

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