1

我有两张表,即价格表(表A)和订单记录(表B)

表 A

SKU Offer Date  Amt
AAA 20120115    22
AAA 20120223    24
AAA 20120331    25
AAA 20120520    28

表 B

Customer   SKU  Order Date
A001       AAA  20120201
B001       AAA  20120410
C001       AAA  20120531

我必须根据订单日期为每个客户检索正确的定价。预期的输出应该是这样的: -

Customer  SKU   Order Date  Amt
A001      AAA   20120201    22
B001      AAA   20120410    25
C001      AAA   20120531    28

谢谢。

4

3 回答 3

2

左连接(或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
于 2012-06-13T06:02:34.533 回答
1

下一次,做你尝试过的东西....

无论如何,这是你的答案!尝试...

Select X.Customer , X.SKU , X.OrderDate , Y.Amt from B as X INNER JOIN A as Y ON X.Order Date= Y. Offer Date

祝你好运...

于 2012-06-13T05:59:48.140 回答
1
SELECT o.Customer, o.SKU, o.[Order Date],
  (SELECT TOP 1 l.Amt
   FROM PriceList l
   WHERE l.[Offer Date] <= o.[Order Date] AND o.SKU = l.SKU
   ORDER BY l.[Offer Date] DESC) AS Amount
FROM
Orders o

根据数据库支持,有些事情可能会有所不同

于 2012-06-13T06:01:47.710 回答