左連接(或NOT EXISTS
子查詢)可用於確保兩個表之間的連接使用訂單日期或之前的價格表中的「最近」行。我認爲這是你想要達到的表之間的關係:
設置:
create table Prices (
SKU char(3) not null,
OfferDate date not null,
Amt int not null
)
go
insert into Prices (SKU, OfferDate, Amt) values
('AAA','20120115', 22),
('AAA','20120223', 24),
('AAA','20120331', 25),
('AAA','20120520', 28)
go
create table Orders (
Customer char(4) not null,
SKU char(3) not null,
OrderDate date not null
)
go
insert into Orders (Customer, SKU, OrderDate) values
('A001','AAA','20120201'),
('B001','AAA','20120410'),
('C001','AAA','20120531')
go
查詢:
select
o.*, /* TODO - Explicit columns */
p.Amt
from
Orders o
inner join
Prices p
on
o.SKU = p.SKU and
o.OrderDate >= p.OfferDate
left join
Prices p_later
on
o.SKU = p_later.SKU and
o.OrderDate >= p_later.OfferDate and
p_later.OfferDate > p.OfferDate
where
p_later.SKU is null
沒有。我不知道如何做日期範圍選擇。 – Bob
你如何知道表A的哪一行與表B的哪一行一致? –
你是如何產生預期結果的?我無法理解它背後的邏輯。你要加入哪兩個表的列? – manurajhada