日期:2014-05-20  浏览次数:20552 次

这样的Sql语句怎么写啊?
A表放的是文章
B表放的是评论,B标中只有文章的ID  
如何按照评论的多少对文章进行排序?

------解决方案--------------------
-- 初始化表 赋值
Declare @A table( TID int, Article nvarchar(4000) )
Declare @B table( PID int, TID int, PContent nvarchar(1000) )

insert into @A
select 1, 'aa ' union
select 2, 'bb ' union
select 3, 'cc ' union
select 4, 'dd '

insert into @B
select 1, 2, 'AA ' union
select 2, 2, 'BB ' union
select 3, 1, 'CC ' union
select 4, 3, 'DD ' union
select 5, 3, 'EE ' union
select 6, 2, 'FF ' union
select 7, 1, 'GG ' union
select 8, 2, 'HH '

--主语句
select A.TID, Article, count(PID) as AAA
from @A A
inner join @B B
on A.TID = B.TID
group by A.TID, Article
order by AAA desc
------解决方案--------------------
declare @a table (aid int,title varchar(30))
insert into @a select '1 ', '新闻 '
union all select '2 ', '文章 '

declare @b table (id int identity ,aid int,total int)
insert into @b select '1 ', '3 '
union all select '2 ', '6 '

select a.aid,a.title,b.total from @a a inner join @b b on a.aid=b.aid order by b.total desc


(2 行受影响)

(2 行受影响)
aid title total
----------- ------------------------------ -----------
2 文章 6
1 新闻 3

(2 行受影响)