After sql server grouping, take the first data of each group

The sql ranking windowing functions ROW_NUMBER, DENSE_RANK, RANK, and NTILE are ranking functions.
The ranking windowing function can use the ORDER BY statement alone, or it can be used together with PARTITION BY.

PARTITION BY is used to group the result set, and a windowing function is applied to each group.

ODER BY Specifies the order of ranking windowing functions. The ORDER BY statement must be used in the ranking windowing function


http://www.cnblogs.com/lanzi/archive/2010/10/26/1861338.html

rank skip ranking dense_rank continue ranking
create table tb_test(name varchar(10),val int,memo varchar(20))
insert into tb_test values('a', 2, 'a2(the second value of a)')
insert into tb_test values('a', 1, 'a1--the first value of a')
insert into tb_test values('a', 3, 'a3: the third value of a')
insert into tb_test values('b', 1, 'b1--the first value of b')
insert into tb_test values('b', 3, 'b3: the third value of b')
insert into tb_test values('b', 2, 'b2b2b2b2')
insert into tb_test values('b', 4, 'b4b4')
insert into tb_test values('b', 5, 'b5b5b5b5b5')
insert into tb_test values('b', 5, 'bb5')
go

--plan 1

select a.* from tb_test a where not exists(select 1 from tb_test where name = a.name and val > a.val) ;

select a.* from tb_test a,(select name,max(val) val from tb_test group by name) b where a.name = b.name and a.val = b.val order by a.name;

select a.* from tb_test a inner join (select name , max(val) val from tb_test group by name) b on a.name = b.name and a.val = b.val order by a.name


--Scenario 2 After grouping, take the first 2 data of each group
select * from (
SELECT  ROW_NUMBER()   
        over   
        (PARTITION By name order by val) as rowId,tb_test.*
FROM tb_test
) t
where rowid <= 2

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326932325&siteId=291194637