簡體   English   中英

Postgresql 表的多列中最大日期的 Select 值

[英]Select value by max date in multiple columns for Postgresql table

假設我有一個返回以下信息的查詢:

+-----------+----------+----------+----------+----------+
| ForeignId | ScoreOne | DateOne  | ScoreTwo | DateTwo  |
+-----------+----------+----------+----------+----------+
| 1         |    1     |2021-06-20|    10    |2021-11-15|
| 1         |    2     |2021-06-21|    11    |2021-11-14|
| 1         |    3     |2021-06-22|    13    |2021-11-13|
| 1         |    4     |2021-06-23|     9    |2021-11-12|
| 1         |    3     |2021-06-24|     7    |2021-11-11|
| 1         |    1     |2021-06-25|     5    |2021-11-10|
| 1         |    2     |2021-06-26|     8    |2021-11-09|
| 2         |    5     |2021-02-11|     9    |2020-07-01|
| 2         |    8     |2021-02-12|     9    |2020-07-02|
| 2         |    9     |2021-02-13|     3    |2020-07-03|
| 2         |    7     |2021-02-14|     5    |2020-07-04|
+-----------+----------+----------+----------+----------+

在這種情況下,我想為具有 max(DateOne) 的行帶來 ScoreOne 值,並為與 max(DateTwo) 位於同一行的 ScoreTwo 帶來相同的值。 如您所見,max(DateOne) 與 max(DateTwo) 不在同一行。 所以基本上結果將是這個:

+-----------+----------+----------+----------+----------+
| ForeignId | ScoreOne | DateOne  | ScoreTwo | DateTwo  |
+-----------+----------+----------+----------+----------+
| 1         |    2     |2021-06-26|    10    |2021-11-15|
| 2         |    7     |2021-02-14|    5     |2020-07-04|
+-----------+----------+----------+----------+----------+

我知道我的查詢將使用GROUP BY ForeignId並且它還同時使用max(DateOne)max(DateTwo) ,但我怎樣才能達到這個結果?

使用 window 函數。 the_table CTE 模擬了您的實際數據。

with the_table (foreignid,scoreone,dateone,scoretwo,datetwo) as
(
 values
  (1, 1, '2021-06-20'::date, 10, '2021-11-15'::date),    
  (1, 2, '2021-06-21', 11, '2021-11-14'),    
  (1, 3, '2021-06-22', 13, '2021-11-13'),    
  (1, 4, '2021-06-23',  9, '2021-11-12'),    
  (1, 3, '2021-06-24',  7, '2021-11-11'),    
  (1, 1, '2021-06-25',  5, '2021-11-10'),    
  (1, 2, '2021-06-26',  8, '2021-11-09'),    
  (2, 5, '2021-02-11',  9, '2020-07-01'),    
  (2, 8, '2021-02-12',  9, '2020-07-02'),    
  (2, 9, '2021-02-13',  3, '2020-07-03'),    
  (2, 7, '2021-02-14',  5, '2020-07-04')     
) 
select distinct on (foreignid)
    foreignid,
    first_value(scoreone) over win_one as "ScoreOne",
    first_value(dateone)  over win_one as "DateOne",
    first_value(scoretwo) over win_two as "ScoreTwo",
    first_value(datetwo)  over win_two as "DateTwo"
from the_table
window win_one as (partition by foreignid order by dateone desc),
       win_two as (partition by foreignid order by datetwo desc);
外國人 分數一 日期一號 分數二 日期二
1 2 2021-06-26 10 2021-11-15
2 7 2021-02-14 5 2020-07-04

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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