create table test(topicId int,parentId int,topic varchar(20),time datetime,name varchar(20))
insert test select 1,0,'主题帖子1','2007-02-01','a'
union all select 2,1,'主题帖子1的回复','2007-02-02','a'
union all select 3,1,'主题帖子1的回复','2007-02-03','b'
union all select 4,0,'主题帖子2','2007-02-02','c'
union all select 5,4,'主题贴子2的回复','2007-02-06','d'select topicId=case parentId when 0 then topicId else parentId end,
主题总数=sum(case parentId when 0 then 1 else 0 end),
回复总数=sum(case when parentId=0 then 0 else 1 end),
最后回复时间=max(time),
主题名称=max(case when parentId=0 then topic else null end),
主题作者=max(case when parentId=0 then name else null end)
from test
group by case parentId when 0 then topicId else parentId enddrop table test/*
1 1 2 2007-02-03 00:00:00.000 主题帖子1   a
4 1 1 2007-02-06 00:00:00.000 主题帖子2   c
*/

解决方案 »

  1.   

    --这样?
    create table test(topicId int,parentId int,topic varchar(20),time datetime,name varchar(20),click int)
    insert test select 1,0,'主题帖子1','2007-02-01','a',6
    union all select 2,1,'主题帖子1的回复','2007-02-02','a',6
    union all select 3,1,'主题帖子1的回复','2007-02-03','b',6
    union all select 4,0,'主题帖子2','2007-02-02','c',8
    union all select 5,4,'主题贴子2的回复','2007-02-06','d',8select topicId=case parentId when 0 then topicId else parentId end,
    主题总数=sum(case parentId when 0 then 1 else 0 end),
    回复总数=sum(case when parentId=0 then 0 else 1 end),
    最后回复时间=max(time),
    主题名称=max(case when parentId=0 then topic else null end),
    主题作者=max(case when parentId=0 then name else null end),
    点击数=max(case when parentId=0 then click else 0 end)
    from test
    group by case parentId when 0 then topicId else parentId enddrop table test/*
    1 1 2 2007-02-03 00:00:00.000 主题帖子1   a 6
    4 1 1 2007-02-06 00:00:00.000 主题帖子2   c 8
    */