This is something I was going to do in code, but wondering if it's possible in SQL? I need to go through a set of records which match a certain criteria, then find a super-set of those records which match a criteria comparing to each of the first set. I can illustrate using an example of books as below:
DECLARE @Books TABLE (
BookId INT,
Title VARCHAR(100),
PublishedUTC DATE,
TotalPages INT
);
INSERT INTO @Books (BookId, PublishedUTC, Title, TotalPages)
VALUES (1, '2001-01-01', 'Stewards of Gondor', 245);
INSERT INTO @Books (BookId, PublishedUTC, Title, TotalPages)
VALUES (2, '2010-02-02', 'Heralds of Highgarden', 71);
INSERT INTO @Books (BookId, PublishedUTC, Title, TotalPages)
VALUES (3, '2010-03-03', 'Tales of Trombones', 1244);
INSERT INTO @Books (BookId, PublishedUTC, Title, TotalPages)
VALUES (4, '2004-04-04', 'Fables of Foibles', 50);
In this example the first criteria is TotalPages > 100. The second criteria is -1 or +1 year of published date.
The first criteria will find book IDs 1 and 3. Now I need to find every book which has a published date either 1 year before, or 1 year after, the published date of each item in the first set. So that will (of course) find Book IDs 1 and 3 themselves, plus Book ID 2 (which was published within 1 year of Book ID 3).
Hope that explains well enough. If possible, can this be done in SQL with just SELECTs, no procedural code? I thought of starting using a WITH, like so:
WITH ManyPages AS (
SELECT b.PublishedUTC FROM @Books b where b.TotalPages > 100
)
SELECT b.BookId
FROM @Books b
WHERE b.PublishedUTC -- ... within 1yr of each PublishedUTC in ManyPages
Would that form work in some way?