Question
The following is a snippet of my data:
Create Table Emps(person VARCHAR(50), started DATE, stopped DATE); Insert Into Emps Values ('p1','2015-10-10','2016-10-10'), ('p1','2016-10-11','2017-10-11'), ('p1','2017-10-12','2018-10-13'), ('p2','2019-11-13','2019-11-13'), ('p2','2019-11-14','2020-10-14'), ('p3','2020-07-15','2021-08-15'), ('p3','2021-08-16','2022-08-16'); I want to use T-SQL to get a count of how many persons fulfil the following criteria at least once - multiples should also count as one:
For a person:
- One of the dates in 'started' (say
s1) is larger than at least one of the dates in 'ended' (saye1) s1ande1are in the same year, to be set manually - e.g. '2021-01-01' until '2022-01-01'
Example expected response
If I put the date range '2016-01-01' until '2017-01-01' somewhere in a WHERE / HAVING clause, the output should be 1 as only p1 has both a start date and an end date that fall in 2016 where the start date is larger than the end date:
s1 = '2016-10-11', and e1 = '2016-10-10'.
Why can't I do this myself
The reason I'm stuck is that I don't know how to do this rowwise comparison between groups. The question requires comparing values across columns (start with end) across rows, within a person ID.
CREATE TABLE...INSERTand a fiddle. "fulfil the following criteria at least once" Does that mean either of the criteria once, or both once? If the latter does it have to be the same row as each other? Also shouldn'tp2be included, as2019-11-14is greater than2019-11-13