根据一列的MAX值从行中选择多列

时间:2018-07-14 03:42:31

标签: sql postgresql

我正在尝试创建一个摘要,以每天每个学生的最佳成绩为基础。

示例数据:

╔════╦════════════╦═══════╦═══════════════════╗
║ 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  ║
╚════╩════════════╩═══════╩═══════════════════╝

所需结果:

╔════════════╦════════════╦═════════════╦═════════════╦══════════════════════╗
║ 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     ║
╚════════════╩════════════╩═════════════╩═════════════╩══════════════════════╝

这是我到目前为止(以及我的问题)的答案:

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

2 个答案:

答案 0 :(得分:5)

下面是简单的解决方案。

替换

date_time as best_score_date_time

使用

(
  array_agg(date_time order by score desc)
)[1]

答案 1 :(得分:2)

     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;