【问题标题】:PostgreSQL: first date cumulative scorePostgreSQL:第一次日期累积分数
【发布时间】:2018-05-31 12:15:58
【问题描述】:

我有这个示例表:

id  date    score
11  1/1/2017 14:32  25.34
4   1/2/2017 12:14  34.34
25  1/2/2017 18:08  37.15
4   3/2/2017 23:42  47.24
4   4/2/2017 23:42  54.12
25  7/3/2017 22:07  65.21
11  9/3/2017 21:02  74.6
25  10/3/2017 5:15  11.3
4   10/3/2017 7:11  22.45

我的目标是计算 id 的累积分数达到 100 (>=) 的第一个 (!) 日期 (YYYY-MM-DD)。为此,我编写了以下代码:

SELECT date(date),id, score,
sum(score) over (partition by id order by date(date) rows unbounded preceding) as cumulative_score
FROM test_q1
GROUP BY id, date, score
Order by id, date

返回:

date    id  score   cumulative_score
1/1/2017    11  25.34   25.34
9/3/2017    11  74.6    99.94
1/2/2017    4   34.34   34.34
3/2/2017    4   47.24   81.58
4/2/2017    4   54.12   135.7
10/3/2017   4   22.45   158.15
1/2/2017    25  37.15   37.15
7/3/2017    25  65.21   102.36
10/3/2017   25  11.3    113.66

我尝试添加 WHERE 累积分数 >= 100 或 HAVING 累积分数 >= 100,但它返回_

错误:列“cumulative_score”不存在 第 4 行:累积分数 >= 100 ^ SQL 状态:42703 字符:206

有人知道怎么解决吗?

谢谢

我的期望是:

date    id  score   cumulative_score
4/2/2017    4   54.12   135.7
7/3/2017    25  65.21   102.36

输出只是 id 和 date。

【问题讨论】:

    标签: postgresql cumulative-sum


    【解决方案1】:

    试试这个:

    with cumulative_sum AS (
        SELECT id,date,sum(score) over( partition by id order by date) as sum from test_q1
    ),
    above_100_score_rank AS (
        SELECT *, rank() over (partition by id order by sum) AS rank 
           FROM cumulative_sum where sum > 100 
    )
    SELECT * FROM above_100_score_rank WHERE rank= 1;
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 2018-06-05
      • 2021-01-24
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多