I have two tables we'll call them TableA
and TableB
.
CREATE TABLE TableA
(
Id int IDENTITY(1,1) PRIMARY KEY,
DateOne Date Not NULL,
);
CREATE TABLE TableB
(
Id int IDENTITY(1,1) PRIMARY KEY,
TableAId int NOT NULL,
DateTwo Date Not NULL,
FOREIGN KEY (TableAId) References TableA(Id)
);
I insert the following data.
INSERT INTO TableA (DateOne)
VALUES ('2020-01-02');
INSERT INTO TableB (TableAId, DateTwo)
VALUES (1,'2021-01-01'),
(1,'2022-02-02'),
(1,'2023-01-01');
I want to write a query that returns all of the Id's of B
where the date is exactly one or more calendar year minus one day from A's date one.
Pseudo code:
SELECT A.Id, b.Id,
FROM A
LEFT JOIN B ON b.AId = A.Id
WHERE (B.DateTwo is anniversary of A.DateOne minus one day.)
The query ran against this data should return the first and last values from the B table as they are equal to exactly one year (minus a day). The middle value should not appear as it is not equal to a an anniversary minus one day.
1条答案
按热度按时间qco9c6ql1#
This is easier in a standards-compliant database , and Transact SQL is not a standards-compliant database. The following suggestion smells approximately like that of @Charlieface with a sign change and runs in TSQL :