我在 DB 中有兩個不同的表,SR 表和 Quotestable。


我已經完成了以下查詢中的兩個表的左連接,
Select
sr.sr#, sr.sub_status, sq.quotes_status, sr.Equipment_status
from svcops_emea.s_sr sr
left join svcops_emea.s_quotes sq on sq.sr# = sr.sr#
Where s.srtype = 'Repair';
我得到帶有重復項的摘錄,因為對于同一個 SR(1-5676068874) 有兩個不同的 quote_status(Quote-Cancelled, Quote-Accepted)
現在我更改了下面的查詢,我從 Quotes 表中獲取了基于最新“創建”日期的唯一資料,但在提取中,它缺少 SR(1-8376068836),因為它不存在于 Quotes 表中。
Select sr.sr#, sr.sub_status, sq.quotes_status, sr.Equipment_status
from svcops_emea.s_sr sr
left join svcops_emea.s_quotes sq on sq.sr# = sr.sr#
inner join
(
Select sr#, max(Created) as maxdate
from svcops_emea.s_quotes
group by sr#
) tm on sq.sr# = tm.sr# and sq.Created = tm.maxdate and sq.sr# = sr.sr#
Where s.srtype = 'Repair'
誰能幫我查詢這種情況,我可以根據日期獲取唯一資料,而不會錯過 SR 表中的任何 SR?
uj5u.com熱心網友回復:
最簡單的解決方案是橫向連接 ( OUTER APPLY),您可以在其中為 sr 行選擇最新的 sq 行。
select sr.sr#, sr.sub_status, sq.quotes_status, sr.equipment_status
from svcops_emea.s_sr sr
outer apply
(
select *
from svcops_emea.s_quotes
where s_quotes.sr# = sr.sr#
order by created desc
fetch first row only
) sq
where sr.srtype = 'repair';
您自己的查詢也很接近。只是,不要加入。使用INorEXISTS用于ON子句中的查找:
Select sr.sr#, sr.sub_status, sq.quotes_status, sr.Equipment_status
from svcops_emea.s_sr sr
left join svcops_emea.s_quotes sq
on sq.sr# = sr.sr#
and (sq.sr#, sq.Created) in
(
Select sr#, max(Created)
from svcops_emea.s_quotes
group by sr#
)
Where s.srtype = 'Repair';
KEEP LAST另一種解決方案是使用 Oracle 的聚合功能獲取最新狀態。還有一個會使用視窗函式,例如MAX OVER.
uj5u.com熱心網友回復:
如果您按S_QUOTES每個CREATEDdate 值的降序排列每個 each 中的行SR#,則可以將該結果外連接到S_SR表中。
查看代碼中的注釋。查詢的第一部分代表樣本資料;查詢從第 13 行開始。
SQL> with
2 s_sr (sr#, sub_status, equipment_status) as
3 (select '1-7576068874', null , 'System running' from dual union all
4 select '1-5676068874', 'In Process', 'System down' from dual union all
5 select '1-8376068836', 'In Process', 'System down' from dual
6 ),
7 s_quotes (sr#, quotes_status, created) as
8 (select '1-7576068874', 'Cancel' , date '2021-08-03' from dual union all
9 select '1-7576068874', 'Open' , date '2021-08-04' from dual union all
10 select '1-5676068874', 'Quote-Cancelled', date '2021-02-03' from dual union all
11 select '1-5676068874', 'Quote-Cancelled', date '2021-02-22' from dual
12 ),
13 t_quotes as
14 -- rank S_QUOTES rows per CREATED column (for each SR#)
15 (select q.*,
16 row_number() over (partition by q.sr# order by created desc) rn
17 from s_quotes q
18 )
19 -- your 1st query, slightly modified - it joins T_QUOTES and has another join condition
20 select sr.sr#, sr.sub_status, sq.quotes_status, sr.Equipment_status
21 from s_sr sr left join t_quotes sq on sq.sr# = sr.sr#
22 and sq.rn = 1;
SR# SUB_STATUS QUOTES_STATUS EQUIPMENT_STAT
------------ ---------- --------------- --------------
1-5676068874 In Process Quote-Cancelled System down
1-7576068874 Open System running
1-8376068836 In Process System down
SQL>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414340.html
標籤:
上一篇:主鍵違規問題oracledb
