SQL 查询问题。。

answer913 2014-05-09 09:30:04

create table test1
(
id int ,
name varchar(20),
parentid int,
createtime datetime
)
insert into test1 select 1,'aaa',0,'2014-05-02 17:03'
insert into test1 select 2,'bbb',0,'2014-05-02 10:05'
insert into test1 select 3,'ccc',0,'2014-05-02 18:03'
insert into test1 select 4,'ddd',0,'2014-05-02 15:03'
insert into test1 select 5,'eee',2,'2014-05-02 16:03'
insert into test1 select 6,'fff',2,'2014-05-02 20:03'
insert into test1 select 7,'ggg',0,'2014-05-02 13:03'
insert into test1 select 8,'hhh',0,'2014-05-02 14:03'

select * from test1
/* 得到结果*/
id name parentid createtime
6 fff 2 2014-05-02 20:03
3 ccc 0 2014-05-02 18:03
1 aaa 0 2014-05-02 17:03
.......
/* 依次按createtime从高到低排序 ,并且过滤parentid 相同的数据


drop table test1
...全文
89 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
answer913 2014-05-09
  • 打赏
  • 举报
回复
谢谢给的思路,已经解决了,
山寨DBA 2014-05-09
  • 打赏
  • 举报
回复
是这样的结果吗:

select a.* from test1 a inner join (
	select parentid,max(createtime) maxcreatetime from test1 where parentid=2 group by parentid
	) b
on a.parentid=b.parentid and a.createtime=b.maxcreatetime
union all
select * from test1 where parentid=0
id name parentid createtime 6 fff 2 2014-05-02 20:03:00.000 1 aaa 0 2014-05-02 17:03:00.000 2 bbb 0 2014-05-02 10:05:00.000 3 ccc 0 2014-05-02 18:03:00.000 4 ddd 0 2014-05-02 15:03:00.000 7 ggg 0 2014-05-02 13:03:00.000 8 hhh 0 2014-05-02 14:03:00.000
山寨DBA 2014-05-09
  • 打赏
  • 举报
回复
引用 4 楼 answer913 的回复:
不好意思各位 ,没有说明清楚,,只是过滤parentid =2 的数据。。
parentid =0的数据全部显示吗?还是说parentid =0的数据需要根据parentid =0 和那么一起过滤?
answer913 2014-05-09
  • 打赏
  • 举报
回复
不好意思各位 ,没有说明清楚,,只是过滤parentid =2 的数据。。
answer913 2014-05-09
  • 打赏
  • 举报
回复
谢谢你的回答,,你这样把parent=0的都过滤掉只剩下一条了, 我想要这样的结果, /* 得到结果*/ id name parentid createtime 6 fff 2 2014-05-02 20:03 3 ccc 0 2014-05-02 18:03 1 aaa 0 2014-05-02 17:03 4 ddd 0 2014-05-02 15:03 8 hhh 0 2014-05-02 14:03 ....... 这样依次的结果 只是过滤parentid =2 的,, .......
Mr_Nice 2014-05-09
  • 打赏
  • 举报
回复
 
SELECT  A.*
FROM    test1 A
WHERE   NOT EXISTS ( SELECT 1
                     FROM   test1 B
                     WHERE  A.parentid = B.parentid
                            AND A.createtime < b.CREATEtime )
/*
id	name	parentid	createtime
3	ccc	0	2014-05-02 18:03:00.000
6	fff	2	2014-05-02 20:03:00.000
*/
山寨DBA 2014-05-09
  • 打赏
  • 举报
回复
是这个结果吗:

select a.* from test1 a inner join (
	select parentid,max(createtime) maxcreatetime from test1 group by parentid) b
on a.parentid=b.parentid and a.createtime=b.maxcreatetime

id name parentid createtime 6 fff 2 2014-05-02 20:03:00.000 3 ccc 0 2014-05-02 18:03:00.000

34,590

社区成员

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

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