【问题标题】:how do I get certain numbers of rows per unique column? [duplicate]如何获得每个唯一列的特定行数? [复制]
【发布时间】:2019-06-14 15:42:10
【问题描述】:

我使用的是 postgresql,我有两列 Country 和 Name。我想为每个国家/地区获取 x 个人的名字。

例如,如果我有这样的数据

Name    Country
"John"  "US"
"Kim"   "KR"
"Mike"  "US"
"Park"  "KR"
"Kim"   "US"
"Doe"   "RU"
"Pou"   "KR"
"John"  "RU"
"Sam"   "RU"
 ...    ...
 ...    ...

并说我想为每个国家/地区获得 2 个 ppl 名称

Name    Country
"John"  "US"
"Mike"  "US"



"Park"  "KR"
"Pou"   "KR"



"Sam"   "RU"
"Doe"   "RU"

有没有办法做这种事情?

【问题讨论】:

  • 您可能想要更具体一点,但您需要的一般查询是 SELECT Name, Country FROM [table] GROUP BY Name, Country ORDER BY Country

标签: sql postgresql


【解决方案1】:

您可以在下面尝试 - 使用 row_number()

select * from
(
SELECT Name, Country, row_number() over(partition by country order by name) as rn
FROM [table] 
)A where rn<=10 [here x=10]

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2020-07-15
    相关资源
    最近更新 更多