SQL return n rows per row value

岁酱吖の 提交于 2020-01-14 04:24:33

问题


Greetings SQL people of all nations.

Simple question, hopefully a simple answer.

I have an Oracle database table with persons' information. Columns are:

FirstName, LastName, BirthDate, BirthCountry

Let's say in this table I have 1500 persons born in Aruba (BirthCountry = "Aruba"), 678 Botswanans (BirthCountry = "Botswana"), 13338 Canadians (BirthCountry = "Canadia").

What query would I need to write extract a sample batch of 10 records from each country? It doesn't matter which 10, just as long as there are 10.

This one query would output 30 rows, 10 rows from each BirthCountry.


回答1:


This will select 10 youngest people from each country:

SELECT  *
FROM    (
        SELECT  p.*,
                ROW_NUMBER() OVER (PARTITION BY birthCountry ORDER BY birthDate DESC) rn
        FROM    persons p
        )
WHERE   rn <= 10



回答2:


This would pick ten random persons, different ones each time you run the query:

select  *
from    (
        select  row_number() over (partition by BirthCountry 
                                   order by dbms_random.value) as rn
        ,       FirstName
        ,       LastName
        ,       BirthDate
        ,       BirthCountry
        from    YourTable
        )
where   rn <= 10


来源:https://stackoverflow.com/questions/16399680/sql-return-n-rows-per-row-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!