日期:2014-05-17  浏览次数:20808 次

.net 评论表获取前10个最新的评论内容(用户不同)
请教一条SQL查询语句。谢谢
评论表 t
字段
id
userid
subject
如何取出最新的10条记录,userid要不同 ,根据id排序
每个usreid只取一条记录
===============
比如:
id     userid   subject
1        1           标题1
2        1           标题2
3        2           标题3
4        3           标题4
5        4           标题5
6        2           标题6
7        3           标题7
8        7           标题8
=============
结果
id
8
7
6
5
2

谢谢

------解决方案--------------------
create  table t
(
id int,
userid int,
subject varchar(20)
)
insert into t 
select 1,1,'标题1' union all
select 2,1,'标题2' union all
select 3,2,'标题3' union all
select 4,3,'标题4' union all
select 5,4,'标题5' union all
select 6,2,'标题6' union all
select 7,3,'标题7' union all
select 8,7,'标题8'
go

with cte as
(
select top 10 max(t1.id)id,t1.userid
from 
t t1 inner join t t2 on t1.userid=t2.userid
group by t1.userid
)
select id,userid
from
cte
order by id desc

------解决方案--------------------

select * from
(
select max(t.id) as [id] from t group by t.userid
) order by [id] desc

------解决方案--------------------
create  table t
(
id int,
userid int,
subject varchar(20)
)
insert into t 
select 1,1,'标题1' union all
select 2,1,'标题2' union all
select 3,2,'标题3' union all
select 4,3,'标题4' union all
select 5,4,'标题5' union all
select 6,2,'标题6' union all
select 7,3,'标题7' union all
select 8,7,'标题8'
go


select top 10  * from
(
select max(t.id) as [id] from t group by t.userid
)t
order by [id] desc

------解决方案--------------------