簡體   English   中英

根據一列的MAX值從行中選擇多列

[英]Select multiple columns from row based on MAX value of a column

我正在嘗試創建一個總結,每個學生每天的最佳成績。

示例數據:

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

以下是簡單的解決方案。

更換

date_time as best_score_date_time

(
  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM