我有一個名為 TASK_CHECK 的表,它看起來像這樣:
| 型別 | 完成日期 |
|---|---|
| 凱達 | 17.12.2021 |
| 知識庫 | 18.12.2021 |
還有一個叫做 TASK_SCHEDULE 的表,它看起來像這樣:
| check_id | 型別 | 約定的日期 |
|---|---|---|
| 201 | 凱達 | 19.12.2021 |
| 202 | 凱達 | 22.12.2021 |
| 203 | 凱達 | 23.12.2021 |
| 204 | 知識庫 | 21.12.2021 |
| 205 | 知識庫 | 23.12.2021 |
現在我需要顯示第一個表,但還有一列,我需要顯示完成日期后發生的第二個表中的第一個下一個 check_id。例如:
| 型別 | 完成日期 | 約定的日期 | check_id |
|---|---|---|---|
| 凱達 | 17.12.2021 | 19.12.2021 | 201 |
| 知識庫 | 18.12.2021 | 23.12.2021 | 204 |
uj5u.com熱心網友回復:
這是一個選項(第 1 - 12 行中的示例資料;您不需要那個 - 您可能感興趣的查詢從第 14 行開始):
SQL> with
2 task_check (type, completion_date) as
3 (select 'KDA', date '2021-12-17' from dual union all
4 select 'KDB', date '2021-12-18' from dual
5 ),
6 task_schedule (check_id, type, scheduled_date) as
7 (select 201, 'KDA', date '2021-12-19' from dual union all
8 select 202, 'KDA', date '2021-12-22' from dual union all
9 select 203, 'KDA', date '2021-12-23' from dual union all
10 select 204, 'KDB', date '2021-12-21' from dual union all
11 select 205, 'KDB', date '2021-12-23' from dual
12 )
13 --
14 select c.type, c.completion_date, s.scheduled_date, s.check_id
15 from task_check c join task_schedule s on s.type = c.type
16 where s.scheduled_date = (select min(s1.scheduled_date)
17 from task_schedule s1
18 where s1.type = s.type
19 and s1.scheduled_date > c.completion_date
20 );
TYP COMPLETION SCHEDULED_ CHECK_ID
--- ---------- ---------- ----------
KDA 17.12.2021 19.12.2021 201
KDB 18.12.2021 21.12.2021 204
SQL>
uj5u.com熱心網友回復:
你可以CROSS JOIN一個橫向派生表:
select c.type, c.completion_date, s.scheduled_date, s.check_id
from task_check c
cross join lateral (select * from task_schedule
where type = c.type
and scheduled_date > c.completion_date
order by scheduled_date
fetch first 1 row only) s
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397720.html
標籤:sql 甲骨文 oracle-sqldeveloper
上一篇:如何合并兩個表以顯示條目歷史更改
下一篇:查詢所有磁區表
