簡體   English   中英

sql:另一個表中 2 列的最大值

[英]sql: max value by 2 columns in another table

我有 2 個表,對於第一個表中的每個 id,我需要在 date_2 列中找到低於 date_1 列中的值的最大值。

表:

表格1

ID 日期_1
1個 01.01.2020
1個 11.01.2020
2個 02.11.2020
2個 02.12.2020
3個 12.12.2020
3個 2021 年 1 月 31 日

表 2

ID 日期_2
1個 2019 年 12 月 30 日
1個 05.01.2020
2個 01.11.2020
2個 2020 年 10 月 30 日
3個 10.11.2020
3個 2020 年 12 月 31 日

需要的結果:

ID 日期_1 id,date_1 內的 max(date_2)
1個 01.01.2020 2019 年 12 月 30 日
1個 11.01.2020 05.01.2020
2個 02.11.2020 01.11.2020
2個 02.12.2020 01.11.2020
3個 12.12.2020 10.11.2020
3個 2021 年 1 月 31 日 2020 年 12 月 31 日

感謝您對此的幫助!

您可以對每一行進行排名(我在這里使用 row_number() 函數進行排名)然后匹配 id 和排名。

with t1 as (select id, date_1,
              row_number() over (partion by id order by date1) as rn
         from table1),
     t2 as (select id, date_2,
            row_number() over (partion by id order by date2) as rn
     from table2 ),
     select id, date1, date2
     from t1 inner join t2 on t1.id = t2.id and t1.rn = t2.rn

您幾乎可以使用反映英語敘述的exists編寫一個簡單的相關查詢:

select id, (   
  select Max(date_2)          /* find max value in the date_2 column */
  from t2 
  where t2.id = t1.id         /* for every id in the first table */
    and t2.date_2 < t1.date_1 /* lower than a value in the date_1 column */
) as "max(date_2) within id,date_1"
from t1;

暫無
暫無

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

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