表a(里程碑):
| PK_id | emp_id | 里程碑日期 |
|---|---|---|
| 1 | 2 | 2022-01-17 |
| 2 | 2 | 2021-03-23 |
| 3 | 2 | 2018-06-29 |
| 4 | 3 | 2018-01-15 |
| 5 | 3 | 2016-02-17 |
| ... | ... | ... |
表 b:
| PK_id | Emp_id | ins_date |
|---|---|---|
| 1 | 2 | 2022-01-20 |
| 2 | 2 | 2019-03-30 |
| 3 | 3 | 2017-06-29 |
我的問題是我想選擇表 A 的地板日期行。但我不知道如何使用該命令。
方法是,在表B的每一行中,確定ins_date和emp_id的列。然后使用該值選擇表A中的日期即下限日期(我不知道如何解釋。但嘗試在下面的示例中理解)。然后在串列中顯示結果。
例如
第 1 行:表 B。ins_date 值為 '2022-01-20',emp_id 為 2。考慮 emp_id = 2 和下限日期 '2022-01-20'(因為大于 2022-01-20 ),所以選擇專案 PK_ID = 1。
第 2 行:表 B。ins_date 值為“2019-03-30”,emp_id 為 2。考慮 emp_id = 2 和“2018-06-29”的下限日期(因為大于 2018-06-29 但小于2021-03-23 ),所以選擇專案 PK_ID = 3。
第 3 行:表 B。ins_date 值為“2017-06-29”,emp_id 為 3。考慮 emp_id = 3 和“2016-02-17”的下限日期(因為大于 2016-02-17 但小于2018-01-15 ),因此選擇專案 PK_ID = 5。
謝謝你,對不起我的英語。
PS我不知道如何解釋問題和細節。但是,如果您編輯文本以使其更易于理解。我強烈允許編輯。
uj5u.com熱心網友回復:
您正在尋找小于或等于 ins_date 的最大里程碑日期。
獲得該日期的兩種方法:
選項1
select b.*, max(a.milestone_date) as floor_milestone_date
from b
join a on a.emp_id = b.emp_id and a.milestone_date <= b.ins_date
group by b.pk_id
order by b.pk_id;
選項 #2
select
b.*,
(
select max(a.milestone_date)
from a
where a.emp_id = b.emp_id and a.milestone_date <= b.ins_date
) as floor_milestone_date
from b;
上面兩個查詢的區別:當ins_date沒有下限里程碑日期時,第一個查詢不回傳b行,而第二個查詢回傳b行,里程碑日期為空。
現在,如果您想從表 a 中獲取更多資訊,請將該表連接到上述查詢之一。
最后的查詢
select ab.*, a.pk_id
from
(
select b.*, max(a.milestone_date) as floor_milestone_date
from b
join a on a.emp_id = b.emp_id and a.milestone_date <= b.ins_date
group by b.pk_id
) ab
join a on a.emp_id = ab.emp_id and a.milestone_date = ab.floor_milestone_date
order by ab.pk_id;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430919.html
標籤:mysql
上一篇:大寫和小寫的第一順序
