如何使用 PostgreSQL 9.2 计算游戏中每个级别的百分位数
How to calculate percentiles for every level in a game using PostgreSQL 9.2
我有 table 游戏日志。像这样:
Level Shuffle_Count
1 3
2 1
2 2
2 1
3 0
3 4
这意味着每当用户玩一个关卡时,都会向 table 添加一行。这些行的关卡数据显示用户玩过哪个关卡,shuffle_count 数据显示该关卡中随机播放的次数。
我想通过计算每一关shuffle_count的中位数来知道每一关发生了多少次shuffle。在下面的代码中,我可以分别找到 2 级的中位数。首先,我创建了一个临时的 table,它对 shuffle_count 进行排序,并将它们分成 4 个带有 ntile 的偶数组。然后我 select 最小值 shuffle_count 在名为 quartile 的新列中的值为 3。
with ranked_test as (
SELECT shuffle_count, ntile(4) OVER (ORDER BY shuffle_count) AS quartile FROM ch.public.game_log WHERE level = 2
)
SELECT min(shuffle_count) FROM ranked_test
WHERE quartile = 3
GROUP BY quartile;
这是在 selecting min shuffle_count 之前创建的 table,其中四分位数 = 3(大约是中位数):
Shuffle_Count quartile
0 1
0 1
2 2
3 2
4 3
8 3
12 4
19 4
到目前为止一切顺利。但问题是我有超过 1000 个级别,我不能为每个级别手动完成。我需要从 1 到 1000 的每个级别的中值 shuffle_count。我知道这可以在 PostgreSQL 9.4 中用一行来完成,但不幸的是我现在没有那个选项。
我无法通过简单的分组依据实现这一目标。我想我需要更复杂的查询,包括 FOR 之类的。
伙计们,你们有什么想法吗?提前致谢。
我认为这应该适用于您的用例:
with ranked_test as (
select
level,
shuffle_count,
ntile(4) over(partition by level order by shuffle_count) quartile
from ch.public.game_log
)
select level, quartile , min(shuffle_count)
from ranked_test
where quartile = 3
group by level, quartile;
这基本上是您的工作查询的扩展版本:
在CTE中,我们去掉了子查询中level
上的过滤器,并将其添加到window函数的partition by
中,而不是[=15] =]
外层查询,我们在select
和group by
子句中添加级别
我有 table 游戏日志。像这样:
Level Shuffle_Count
1 3
2 1
2 2
2 1
3 0
3 4
这意味着每当用户玩一个关卡时,都会向 table 添加一行。这些行的关卡数据显示用户玩过哪个关卡,shuffle_count 数据显示该关卡中随机播放的次数。
我想通过计算每一关shuffle_count的中位数来知道每一关发生了多少次shuffle。在下面的代码中,我可以分别找到 2 级的中位数。首先,我创建了一个临时的 table,它对 shuffle_count 进行排序,并将它们分成 4 个带有 ntile 的偶数组。然后我 select 最小值 shuffle_count 在名为 quartile 的新列中的值为 3。
with ranked_test as (
SELECT shuffle_count, ntile(4) OVER (ORDER BY shuffle_count) AS quartile FROM ch.public.game_log WHERE level = 2
)
SELECT min(shuffle_count) FROM ranked_test
WHERE quartile = 3
GROUP BY quartile;
这是在 selecting min shuffle_count 之前创建的 table,其中四分位数 = 3(大约是中位数):
Shuffle_Count quartile
0 1
0 1
2 2
3 2
4 3
8 3
12 4
19 4
到目前为止一切顺利。但问题是我有超过 1000 个级别,我不能为每个级别手动完成。我需要从 1 到 1000 的每个级别的中值 shuffle_count。我知道这可以在 PostgreSQL 9.4 中用一行来完成,但不幸的是我现在没有那个选项。
我无法通过简单的分组依据实现这一目标。我想我需要更复杂的查询,包括 FOR 之类的。
伙计们,你们有什么想法吗?提前致谢。
我认为这应该适用于您的用例:
with ranked_test as (
select
level,
shuffle_count,
ntile(4) over(partition by level order by shuffle_count) quartile
from ch.public.game_log
)
select level, quartile , min(shuffle_count)
from ranked_test
where quartile = 3
group by level, quartile;
这基本上是您的工作查询的扩展版本:
在CTE中,我们去掉了子查询中
level
上的过滤器,并将其添加到window函数的partition by
中,而不是[=15] =]外层查询,我们在
select
和group by
子句中添加级别