为用户获取百分位数

问题描述 投票:0回答:1

我有一个这样的表:

Id, ReportId, UserId  
1      1        1  
2      2        1  
3      3        1
4      4        1
5      1        2
6      2        2
7      3        2
8      1        3
9      2        3
10     1        4

我的表有成千上万的记录,上面只是为了理解问题而简化的表结构的一个例子。

我试图根据用户阅读的报告数量来确定用户所处的百分位数。

我一直在研究PERCENTILE_CONT和PERCENTILE_DISC函数,但我无法正确理解它们。 https://docs.microsoft.com/en-us/sql/t-sql/functions/percentile-cont-transact-sql

最让我困惑的是,我认为这些功能正在试图找到第50个百分点,而不是特定记录的百分位数。

也许我只是没有正确理解这一点。有没有更好的办法?

编辑:

澄清。我想知道特定用户(在这种情况下,id为1的用户)的百分位数取决于他们阅读了多少报告。如果他们阅读的报告最多,那么他们的百分位数就会更高,这个百分位数是多少?假设确切地说有100个用户,那么阅读大多数报告的人将是第1百分位数。

sql sql-server
1个回答
2
投票

更新#2

其中一个应该这样做:

select 
        a.UserId, 
        a.reports_read, 
        PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY a.reports_read) OVER (partition by UserId) AS percentile_d, 
        PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY a.reports_read) OVER (partition by UserId) AS percentile_c,
        PERCENT_RANK() OVER(ORDER BY a.reports_read ) percent_rank,
        CUME_DIST() OVER(ORDER BY a.reports_read ) AS cumulative_distance     
    from 
        (select UserId, count(distinct(ReportId)) as reports_read
            from #tmp
            group by UserId
        ) a 

它给出了以下结果:

UserId  reports_read    percentile_d    percentile_c    percent_rank    cumulative_distance
4       1               1               1               0               0.25
3       2               2               2               0.33333         0.5
2       3               3               3               0.66667         0.75
1       6               6               6               1               1

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.