-
Erland Sommarskog 78,026 Reputation points MVP
2022-10-29T21:03:30.59+00:00 SELECT * FROM #TestDate a WHERE EXISTS (SELECT * FROM #TestDate b WHERE b.CONTRACTCODE = a.CONTRACTCODE AND b.STARTDATE <= a.ENDDATE AND b.ENDDATE >= a.STARTDATE AND NOT (b.STARTDATE = a.STARTDATE AND b.ENDDATE = a.ENDDATE))
Hi,
Your table structure is problematic since you have no way to identify rows if the columns has the same value
For example, let's add these two rows:
INSERT INTO TestDate (CONTRACTCODE, STARTDATE, ENDDATE) VALUES ('RO_AGN_99', {d '2020-01-11'}, {d '2021-02-11'})
INSERT INTO TestDate (CONTRACTCODE, STARTDATE, ENDDATE) VALUES ('RO_AGN_99', {d '2020-01-11'}, {d '2021-02-11'})
If you had for example identification column like ID INT IDENTITY primary key
then the solution was simple (very very very close to Erland solution)
SELECT *
FROM TestDate a
WHERE EXISTS (
SELECT *
FROM TestDate b
WHERE
b.CONTRACTCODE = a.CONTRACTCODE
AND b.STARTDATE <= a.ENDDATE
AND b.ENDDATE >= a.STARTDATE
AND NOT a.id = b.id
)
GO
Unfortunately since you have no such column, you can use something like ROW_NUMBER function to add identification on the fly. Here is a solution for your case without identification column
;With MyCTE as (
SELECT CONTRACTCODE, STARTDATE, ENDDATE, ID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM TestDate a
)
SELECT CONTRACTCODE, STARTDATE, ENDDATE
FROM MyCTE a
WHERE EXISTS (
SELECT *
FROM MyCTE b
WHERE
b.CONTRACTCODE = a.CONTRACTCODE
AND b.STARTDATE <= a.ENDDATE
AND b.ENDDATE >= a.STARTDATE
AND NOT a.id = b.id
)
GO
Please check if this solve your need