|
Posted by Erland Sommarskog on 01/10/07 23:35
M@ (mattcushing@gmail.com) writes:
> If I have a query I am writing, I can use the top 10 function to bring
> back the top 10 rows. That's all fine if all I want is 10 rows.
>
> What if I have a grouped query, and I have 5 entities that I want 10
> rows each from? ie, I have 5 buildings I would want max 50 rows.
>
> I tried Union, which works if you want them all, but I would like the
> user to be able to supply me a list of buildings and be able to bring
> back 10 rows for each building they ask for.
>
> Possible?
>
> I was thinking of creating a view, or writing a while and looping
> through with a query, but I am unsure where to begin.
select building
from (select building, row_number() over(partition by groupid,
order by height desc) AS rn
from buildings) AS b
where rn <= 10
This solution requires SQL 2005. If you are using SQL 2000, your best
bet is probably to insert data into a temp table with an IDENTITY column
and work from that one.
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
Navigation:
[Reply to this message]
|