gpt4 book ai didi

sql - postgres - 可以使用窗口函数来解决这个查询吗?

转载 作者:行者123 更新时间:2023-12-03 02:10:28 25 4
gpt4 key购买 nike

我有以下架构中的数据:

| user_id | date   | score  |
| ------- | ------ | ------ |
| 1 | 201901 | 1 |
| 1 | 201902 | 2 |
| 1 | 201903 | 3 |
| 2 | 201901 | 1 |
| 2 | 201902 | -1 |
| 2 | 201903 | 2 |

我需要得出以下结果:

| user_id | one_score  | two_score | three_score | max_score | min_score |
| ------- | ---------- | --------- | ----------- | --------- | --------- |
| 1 | 1 | 3 | 6 | 3 | 1 |
| 2 | 1 | 0 | 2 | 2 | -1 |

请注意,one_score 是第一个结果的总和,two_score 是前两个结果的总和,而 Three_score 是与 user_id 关联的前三个结果的总和。

到目前为止,我的查询的总体布局是:

SELECT
MAX(score),
MIN(score)
FROM scores
GROUP BY user_id

我不确定计算 one_score、two_score 和 Three_score 的最佳方法是什么。一种可能的方法是为每种情况编写一个自定义聚合函数,该函数将整个列作为输入:

SELECT
MAX(score),
MIN(score),
one_score(score),
two_score(score),
three_score(score)
FROM scores
GROUP BY user_id

我想知道是否有比这涉及窗口函数更好的方法。似乎我应该在每一列中更改的是应用 sum 函数的行数,而不是为每种情况编写单独的函数。我如何为滚动总和 one_score、two_score、 Three_score 编写一个窗口函数?

注意 - 这是根据“现实世界”案例建模的简化案例,有两个区别:

  1. 它将是一个数学表达式,而不是求和函数
  2. 范围不再是 1、2、3,而是变化很大(最后 10 个、最后 30 个、最后 50 个等)。

最佳答案

您可以使用 row_number() 窗口函数对每个用户的行进行编号,然后将这些数字用于 FILTER 子句以 sum().

SELECT x.user_id,
sum(x.score) FILTER (WHERE x.rn <= 1) one_score,
sum(x.score) FILTER (WHERE x.rn <= 2) two_score,
sum(x.score) FILTER (WHERE x.rn <= 3) three_score,
max(x.score) max_score,
min(x.score) min_score
FROM (SELECT s.user_id,
s.score,
row_number() OVER (PARTITION BY s.user_id
ORDER BY s.date) rn
FROM scores s) X
GROUP BY x.user_id;

db<>fiddle

关于sql - postgres - 可以使用窗口函数来解决这个查询吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com