0
INNER JOIN Sales_Category c1 ON c1.MPCID = c1.Category_Id 
WHERE Date_of_Purchase > DATEADD(d, -90, getdate()) 
ORDER BY c1.MPCID

Table1-OrderDetails包含字段= Bill_To_Id, MPC, Order_value,Category_Id

Table2-Sales_Category包含字段 = `MPCID

4

1 回答 1

0

我仍然不清楚您是否希望选择查询结果中的 Category_Id 来自 Sales_Category 而不是 OrderDetails,或者您是否真的想用 Sales_Category 中的相应值更新 OrderDetails 中的数据。因此,我将提供两者,您可以从那里获取。我会警告您在运行更新语句时要小心,因为您实际上是在更改数据。

create table OrderDetails
(
  OrderLine_Id int
, OrderId int
, Bill_to_Id int
, Date_of_Purchase date
, MPC int
, Order_Value int
, Category_Id int
)

create table Sales_Category
(
  Category_Id int
, MPC int
)

insert into OrderDetails values
  (4, 711, 8566, '2018-05-11', 5450, 10000, null)
, (8, 5555, 8123, '2020-03-11', 6700, 20000, null)
, (103, 456, 123456, '2019-02-05', 71883, 30000, null)
, (1, 123, 67999, '2020-02-08', 7899, 40000, null)
, (2, 678, 9913, '2020-01-11', 9908, 50000, null)
, (3, 488, 98564, '2020-02-14', 999, 60000, null)
, (null, null, null, null, null, null, null)

insert into Sales_Category values
  (1, 5450)
, (2, 6700)
, (3, 9908)

-- OrderDetails populated with sample data
select * from OrderDetails

-- Sales_Category populated with sample data
select * from Sales_Category

-- this will get Category_Id from Sales_Category rather than OrderDetails
select 
  od.Bill_to_Id
, od.MPC
, od.Order_Value
, sc.Category_Id
from OrderDetails od
left join Sales_Category sc on od.MPC = sc.MPC
where od.Date_of_Purchase > DATEADD(d, -90, getdate())

-- this shows nothing has actually been updated yet
select * from OrderDetails

update OrderDetails
set Category_Id = sc.Category_Id
from OrderDetails od
inner join Sales_Category sc on od.MPC = sc.MPC
where od.Date_of_Purchase > DATEADD(d, -90, getdate())

-- this shows that Category_Id in OrderDetails has been updated where the
-- MPC values match and the Date_of_Purchase is within the last 90 days
select * from OrderDetails

这是此代码的演示。这是您在提出问题时应该提供的类型,让某人尽可能容易地帮助您。

于 2020-04-07T17:34:19.420 回答