自解压排名和密集的排名例子假设你使用SQL Server 2008或更新。
declare @Person Table (personID int identity, person varchar(8));
insert into @Person values ('Brett'),('Sean'),('Chad'),('Michael'),('Ray'),('Erik'),('Queyn');
declare @Orders table (OrderID int identity, PersonID int, Desciption varchar(32), Amount int);
insert into @Orders values (1, 'Shirt', 20),(1, 'Shoes', 50),(2, 'Shirt', 22),(2, 'Shoes', 20),(3, 'Shirt', 20),(3, 'Shoes', 50),(3, 'Hat', 20),(4, 'Shirt', 20),(5, 'Shirt', 20),(5, 'Pants', 30),
(6, 'Shirt', 20),(6, 'RunningShoes', 70),(7, 'Shirt', 22),(7, 'Shoes', 40),(7, 'Coat', 80);
with a as
(
Select
person
, o.Desciption
, o.Amount
, rank() over(partition by p.personId order by Amount) as Ranking
, Dense_rank() over(partition by p.personId order by Amount) as DenseRanking
from @Person p
join @Orders o on p.personID = o.PersonID
)
select *
from a
where Ranking <= 2 -- determine top 2, 3, etc.... whatever you want.
order by person, amount
嗨,我正在使用SQL SERVER 2012我会给这个欢呼 – 2013-03-25 17:02:07