5

Lets say there was a dataset like this

Grp   | Name (Unique)
A     | Joe
B     | Bob
C     | Jill
B     | James

If there were about 50 of each group (A,B,C) how do I return a result with only the top 5 from each group without doing something like this

SELECT TOP 5 * FROM TABLE WHERE Grp = 'A' UNION ALL
SELECT TOP 5 * FROM TABLE WHERE Grp = 'B' UNION ALL
SELECT TOP 5 * FROM TABLE WHERE Grp = 'C'
4

1 に答える 1

10

試す

SELECT Grp, Name FROM(
 SELECT Grp, Name, RANK() OVER (Partition By Grp ORDER By Name DESC) as rankname
   FROM YourTable)
    WHERE rankname <= 5

編集:これはあなたが望むものだと思います。そうでない場合は、コメントしていただければ対応いたします。

于 2013-02-21T04:12:08.113 に答える