Hello, I have two tables (Supplied and Orders) that are related by a serial number and date. The dates do not match they are just close. I came up with a rank to find matching data, but it does not work if there are more Supplied records than Orders for a given serial number. To demonstrate I have:
CREATE TABLE #SuppliedData (SerialNum VARCHAR(50), TDate DATE);
INSERT INTO #SuppliedData (SerialNum, TDate) VALUES
('353223104176111','2021-03-11'),
('353223104176111','2021-07-15'),
('357379091537024','2021-03-03'),
('357379091537024','2021-06-04'),
('358230100878942','2021-07-07');
CREATE TABLE #OrderData (SKU VARCHAR(50), OrdDate DATETIME, OrdNum INT);
INSERT INTO #OrderData (SKU, OrdDate, OrdNum) VALUES
('353223104176111','2021-03-17 15:50:40.453', 163705600),
('353223104176111','2021-07-20 15:13:54.057', 172160150),
('357379091537024','2021-06-15 11:47:52.117', 169843363),
('358230100878942','2021-07-07 19:25:46.980', 171359335),
('358230100878942','2021-07-08 13:01:59.863', 171399027);
CREATE TABLE #CurrentOutput (SerialNum VARCHAR(50), ODate DATE, OrdNum INT);
INSERT INTO #CurrentOutput (SerialNum, ODate, OrdNum) VALUES
('353223104176111','2021-03-11', 163705600),
('353223104176111','2021-07-15', 172160150),
('357379091537024','2021-03-03', 169843363),
('357379091537024','2021-06-04', NULL),
('358230100878942','2021-07-07', 171399027);
CREATE TABLE #WantedOutput (SerialNum VARCHAR(50), ODate DATE, OrdNum INT);
INSERT INTO #WantedOutput (SerialNum, ODate, OrdNum) VALUES
('353223104176111','2021-03-11', 163705600),
('353223104176111','2021-07-15', 172160150),
('357379091537024','2021-03-03', NULL),
('357379091537024','2021-06-04', 169843363),
('358230100878942','2021-07-07', 171399027);
For serial number 357379091537024 there is only one record in the orders table but two records in the supplied table. My logic populates the order number but for the wrong date.
If you can point me to a solution I would be grateful.
Basically I need a way to combine the tables #SuppliedData and #OrderData on serial number and date to get the desired result.
This is my first post for some time as I have had some job interruption. I hope I have the enough info here.