SQL Query以获得拥有最高Nth百分位数内的朋友的用户

时间:2016-03-06 01:44:22

标签: sql amazon-redshift

我有兴趣让社交网络数据库中排名前10位的朋友。

下面的代码段会获得拥有最多朋友数量的所有用户。

SELECT
    h.name,
    h.grade
FROM
    highschooler h,
    friend f
where
    h.id = f.id1
group by
    f.id1
having
    count(f.id2) <= (
        select
            max(r.c)
        from
        (
            select
                count(id2) as c
            from
                friend
            group by
                id1
        ) as r)

我的数据库看起来像这样:

Highschooler ( ID, name, grade ) 
  

有一名高中生有一个特定的ID,并且在某个等级中有一个名字。

Friend ( ID1, ID2 ) 
  

ID1的学生是ID2学生的朋友。友谊是相互的,所以如果(123,456)在朋友表中,那么(456,123)。

我想知道是否可以使用百分位函数代替MAX函数。有没有人对如何让拥有最高百分位数的朋友的用户有任何想法?

任何帮助都会受到超级赞赏!

1 个答案:

答案 0 :(得分:1)

您可以使用可以解决您的用例的PERCENTILE_DISC。您可以阅读有关here

的更多信息

简单的例子:

select sellerid, qty, percentile_cont(0.9) 
within group (order by qty)  -- sort criteria on the field 
over(partition by sellerid) as median from winsales -- partition;