sql查询语句,来人帮忙看看。
create table [New_CommentInfo]
(
Id int identity(1,1) primary key
,[Pageid] int
,[Email]nvarchar(50)
,[Comment]nvarchar(512)
,[Addtime]datetime
,[Isdelete]int
)
insert into [New_CommentInfo] values(1,'xxx1@cc.com','1可以的。',GETDATE(),0)
insert into [New_CommentInfo] values(1,'xxx2@cc.com','3可以的。','2013-09-07 14:42:12',0)
insert into [New_CommentInfo] values(1,'xxx3@cc.com','2可以的。','2013-09-09 12:12:12',0)
create table [New_ReplyInfo](
[Id] int identity(1,1) primary key
,[Commentid] int
,[Email] nvarchar(50)
,[Reply] nvarchar(512)
,[Addtime] datetime
,[Isdelete] int)
insert into [New_ReplyInfo] values(1,'xxx2@cc.com','我也期待xxx2@cc.com',GETDATE(),0)
insert into [New_ReplyInfo] values(1,'xxx4@cc.com','我也期待xxx4@cc.com',GETDATE(),0)
insert into [New_ReplyInfo] values(2,'xxx4@cc.com','我也期待xxx4@cc.com',GETDATE(),0)
select tt.Pageid, tt.Email, tt.Comment,tt.Addtime
from (select t.Pageid,
t.Email,
t.Comment,
t.Addtime,
row_number() over(order by t.Addtime desc) rn
from New_CommentInfo t
union all
select t1.Pageid, t2.Email,t2.Reply,t2.Addtime,t1.rn
from (select t.Pageid,
t.Email,
t.Comment,
t.Addtime,
row_number() over(order by t.Addtime desc) rn
from New_CommentInfo t) t1,
New_ReplyInfo t2
where t1.Pageid = t2.Commentid) tt
order by rn, Addtime desc
select Id,Email,type,Comment,Addtime,Isdelete,Pageid
from
(select Id,Email,Comment,convert(varchar(20),Addtime,120) 'Addtime',Pageid,'评论' 'type',
convert(varchar(20),Addtime,120) 'Addtime2',Isdelete,0 'lv'
from New_CommentInfo
union all
select a.Commentid,a.Email,a.Reply,convert(varchar(20),a.Addtime,120) 'Addtime',b.Pageid,'回复' 'type',
convert(varchar(20),b.Addtime,120) 'Addtime2',a.Isdelete,1 'lv'
from New_ReplyInfo a
inner join New_CommentInfo b on a.Commentid=b.Id
) t order by Addtime2 desc,lv
/*
Id Email type Comment Addtime Isdelete Pageid
----------- ---------------- ---- ------------------------------ -------------------- ----------- -----------
1 xxx1@cc.com 评论 1可以的。 2013-09-24 16:41:08 0 1
1 xxx2@cc.com 回复 我也期待xxx2@cc.com 2013-09-24 16:41:17 0 1
1 xxx4@cc.com 回复 我也期待xxx4@cc.com 2013-09-24 16:41:17 0 1
3 xxx3@cc.com 评论 2可以的。 2013-09-09 12:12:12 0 1
2 xxx2@cc.com 评论 3可以的。 2013-09-07 14:42:12 0 1
2 xxx4@cc.com 回复 我也期待xxx4@cc.com 2013-09-24 16:41:17 0 1
(6 row(s) affected)
*/