下面是我的示例表和行

create table com (company text,val int);


insert into com values ('com1',1),('com1',2),('com1',3),('com1',4),('com1',5);

insert into com values ('com2',11),('com2',22),('com2',33),('com2',44),('com2',55);

insert into com values ('com3',111),('com3',222),('com3',333),('com3',444),('com3',555);

我想得到每家公司的前三名价值,预期产出是:
company  val
---------------
com1     5
com1     4
com1     3
com2     55
com2     44
com2     33
com3     555
com3     444
com3     333

最佳答案

试试这个:

SELECT company, val FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY
             company order by val DESC) AS Row_ID FROM com
) AS A
WHERE Row_ID < 4 ORDER BY company

--Quick Demo Here...

10-08 04:38