每个用户id sql查询获取两条记录

时间:2014-10-07 10:38:40

标签: sql sql-server

我正在获取数据

1 34 abc5
1 24 abc3
1 12 abc2
1 24 abc1
1 34 abc6
1 34 abc76
1 24 ab1c243
1 24 abc243
1 34 abc243
1 34 abc243

来自我的查询..有没有办法得到这样的输出

我的查询

SELECT * FROM table2
WHERE (abc2 IN  (SELECT * FROM table3 AS f INNER JOIN
table1 AS u ON u.id_usr = f.userLogedin_id
WHERE      (u.id_usr = '13'))) AND (publish_status = '3')
ORDER BY guser_ID

1 34 abc5
1 34 abc6
1 24 abc3
1 24 abc1
1 12 abc2

即。 orderby desc并限制为每个唯一用户2 ..在这种情况下,34,24和12是唯一用户

2 个答案:

答案 0 :(得分:2)

试试这个..

with cte as
(
select row_number() over (partition by <col2> order by <col2> desc) as id, col1,col2,col3 from <tablename>
)
select * from cte where id<=2

答案 1 :(得分:0)

declare @t table (id int,value int,name varchar(10))
insert into @t (id,value,name)values (1,34,'abc5')
insert into @t (id,value,name)values (1,24,'abc3')
insert into @t (id,value,name)values (1,12,'abc2')
insert into @t (id,value,name)values (1,24,'abc1')
insert into @t (id,value,name)values (1,34,'abc6')
insert into @t (id,value,name)values (1,34,'abc76')
insert into @t (id,value,name)values (1,24,'ab1c243')
insert into @t (id,value,name)values (1,24,'abc243')
insert into @t (id,value,name)values (1,34,'abc243')
insert into @t (id,value,name)values (1,34,'abc243')

SELECT  t.*
FROM    (
        SELECT  DISTINCT value
        FROM    @t
        ) tt
CROSS APPLY
        (
        SELECT  TOP 2 *
        FROM    @t t
        WHERE   t.value = tt.value
        ORDER BY
                1 DESC
        ) t