【发布时间】:2013-04-06 09:24:50
【问题描述】:
我对 SQL 相当陌生,正在解决一些实践问题。我有一个示例 Twitter 数据库,我正在尝试根据关注者数量找到每个位置的前 3 名用户。
这是我正在使用的表格:
id_follower_location
id | followers | location
-----------------+-----------+----------
id28929238 | 1 | Toronto
id289292338 | 1 | California
id2892923838 | 2 | Rome
.
.
locations
location
----------------------
Bay Area, California
London
Nashville, TN
.
.
我已经能够通过以下方式找到“顶级”用户:
create view top1id as
select location,
(select id_followers_location.id from id_followers_location
where id_followers_location.location = locations.location
order by followers desc limit 1
) as id
from locations;
create view top1 as
select location, id,
(select followers from id_followers_location
where id_followers_location.id = top1id.id
) as followers
from top1id;
我能够想出解决这个问题的唯一方法是找出“Top 1st”、“Top 2nd”、“Top 3rd”,然后使用union 将它们组合起来。这是正确/唯一的方法吗?还是有更好的办法?
【问题讨论】:
-
一个用户可以拥有多个位置吗?
-
@FoolishSeth 对 postgres 是,对用户没有多个位置。谢谢
-
像大多数此类问题一样,您忘了提及如何处理关系?当 5 个人分享相同数量的关注者时,您想返回什么?您希望每个位置恰好三行吗?如何决定?随机的?随意的?其他标准?
标签: sql postgresql greatest-n-per-group window-functions top-n