セットアップ:
create table Sales
(
sale_date DATE,
sales_rep_name NVARCHAR(100),
sales_rep_id INT,
)
GO
insert into Sales VALUES
('20161004', 'Old man', 123),
('20161104', 'Smith, John', 12345),
('20161115', 'Smith, John', 12345)
GO
create table Employees
(
sales_rep_name NVARCHAR(100),
sales_rep_id INT,
supervisor NVARCHAR(100),
date_from DATE,
date_to DATE
)
GO
テスト:
INSERT INTO Employees VALUES ('Smith, John', 12345, 'Jones, Jim', '20160101', '20160611'),
('Smith, John', 12345, 'Hall, Tom', '20160711', '99991231')
GO
-- gets all sales where INNER JOIN will go
-- even if LEFT JOIN is used, BETWEEN applied to NULL will rule out some records
SELECT S.sale_date, E.sales_rep_name, S.sales_rep_name, E.supervisor
FROM Sales S
JOIN Employees E ON S.sales_rep_id = E.sales_rep_id
AND S.sale_date BETWEEN E.date_from and E.date_to
UNION ALL
-- just NULL the columns for the rest of the records
SELECT S.sale_date, NULL, S.sales_rep_name, NULL
FROM Sales S
WHERE NOT EXISTS (SELECT 1 FROM Employees E WHERE E.sales_rep_id = S.sales_rep_id AND S.sale_date BETWEEN E.date_from and E.date_to)
GO
コードにカンマがありません。 – wildplasser
使用するDBMSを指定してください –
@EmilHolub SQL Server 2016 – user3067478