I have 2 tables :
CREATE TABLE #Table1(Name varchar(10), Date date, Type varchar(10));
INSERT INTO #TABLE1
VALUES
('aa', '2018-09-10', 'Client'),
('bb', '2018-10-12', 'Client'),
('cc', '2018-10-16', 'Client'),
('dd', '2018-11-12', 'Client'),
('ee', '2018-10-15', 'Client'),
('ff', '2018-11-17', 'Client'),
('gg', '2018-12-12', 'Client'),
('tt', '2018-11-11', 'Server'),
('kk', '2018-12-15', 'Server');
CREATE TABLE #Table2(ID INT, Type varchar(10), DateCreated date);
INSERT INTO #Table2
VALUES
(1,'Client', '2018-11-25'),
(2,'Client', '2018-10-25'),
(3,'Client', '2018-11-17'),
(4,'Client', '2018-09-25'),
(5,'Client', '2018-11-10'),
(6,'Client', '2018-12-05'),
(7,'Client', '2018-11-02'),
(8,'Server', '2018-11-19'),
(9,'Server', '2018-12-10');
Expected result :
ID Type Date Created Name
1 Client 2018-11-25 ff
2 Client 2018-10-25 cc
3 Client 2018-11-17 ff
4 Client 2018-09-25 aa
5 Client 2018-11-10 cc
6 Client 2018-12-05 ff
7 Client 2018-11-02 cc
8 Server 2018-11-19 tt
9 Server 2018-12-10 tt
So basically I want for each ID from Table 2 the name from Table 1 based on the rule : If the type is the same , I want to return the name when the difference between Date Created and Date is min .
For example, for ID 6 , the query should return the name ff because the min difference between 05.12.2018 and any date from Table 1 is 18 . ( Date 17.11.2018 )
Date Created >= Date as a rule .
I've tried to create a SQL query but without results .
Can you please help me with this ?
kk
, nottt
?dd
notff
for the expected row.