[英]Select multiple columns from row based on MAX value of a column
I am trying to create a summary with the best score of each student per day. 我正在尝试创建一个总结,每个学生每天的最佳成绩。
Example data: 示例数据:
╔════╦════════════╦═══════╦═══════════════════╗
║ id ║ student_id ║ score ║ date_time ║
╠════╬════════════╬═══════╬═══════════════════╣
║ 1 ║ 1 ║ 5 ║ 2018-07-01 9:30 ║
║ 2 ║ 1 ║ 3 ║ 2018-07-01 15:30 ║
║ 3 ║ 1 ║ 7 ║ 2018-07-02 8:30 ║
║ 4 ║ 2 ║ 7 ║ 2018-07-01 9:30 ║
║ 5 ║ 2 ║ 8 ║ 2018-07-01 15:30 ║
║ 6 ║ 2 ║ 8 ║ 2018-07-02 8:30 ║
║ 7 ║ 3 ║ 4 ║ 2018-07-02 10:30 ║
║ 8 ║ 3 ║ 10 ║ 2018-07-02 13:45 ║
╚════╩════════════╩═══════╩═══════════════════╝
Desired result: 所需结果:
╔════════════╦════════════╦═════════════╦═════════════╦══════════════════════╗
║ student_id ║ date ║ score_total ║ best_score ║ best_score_date_time ║
╠════════════╬════════════╬═════════════╬═════════════╬══════════════════════╣
║ 1 ║ 2018-07-01 ║ 8 ║ 5 ║ 2018-07-01 9:30 ║
║ 1 ║ 2018-07-02 ║ 7 ║ 7 ║ 2018-07-02 8:30 ║
║ 2 ║ 2018-07-01 ║ 15 ║ 8 ║ 2018-07-01 15:30 ║
║ 2 ║ 2018-07-02 ║ 8 ║ 8 ║ 2018-07-02 8:30 ║
║ 3 ║ 2018-07-02 ║ 14 ║ 10 ║ 2018-07-02 13:45 ║
╚════════════╩════════════╩═════════════╩═════════════╩══════════════════════╝
This is what I got so far (and my question): 这是我到目前为止(和我的问题)得到的:
SELECT
student_id,
date_time::date as date,
SUM(score) as score_total,
MAX(score) as best_score,
date_time as best_score_date_time -- << HOW TO GET THIS ONE?
FROM
score
GROUP BY
student_id,
date_time::date
Below is the simple solution. 以下是简单的解决方案。
Replace 更换
date_time as best_score_date_time
with 与
( array_agg(date_time order by score desc) )[1]
SELECT A.student_id,
A.date,
A.score_total,
A.score AS best_score,
A.best_score_date_time
FROM
(
SELECT student_id,
date_time::date AS date,
SUM( score ) OVER ( PARTITION BY date_time::date ) AS score_total,
score,
RANK( ) OVER ( PARTITION BY date_time::date ORDER BY score DESC ) AS rnk,
date_time
FROM score
) A
WHERE A.rnk = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.