Greetings,
I have a Table containing multiple records with Phase Dates. I need to check to ensure each Phase Date does not overlap the prior Phase Dates.
My Table data is similar to the following:
REC_ID | ITEM_ID | PHASE_NAME | PHASE_DATE | Notes... |
---|---|---|---|---|
0001 | 01 | Phase A | 2022-02-01 | First Ph of REC 0001 |
0001 | 02 | Phase B | 2022-02-02 | PhB after Prior Ph means Pass |
0001 | 03 | Phase C | 2022-01-01 | PhC before Prior Phs means Fail |
0001 | 04 | Phase D | 2022-02-03 | PhD after Prior Phs means Pass |
0002 | 05 | Phase A | 2021-12-01 | First Ph of REC 0002 |
0002 | 06 | Phase B | 2021-11-20 | PhB before Prior Phs means Fail |
0002 | 07 | Phase C | 2021-12-03 | PhC after Prior Phs means Pass |
0002 | 08 | Phase D | 2021-12-02 | PhD before PhC means Fail |
etc...
The current query that I have is as follows:
SELECT r.[REC_ID]
,r.[ITEM_ID]
,r.[PHASE_NAME]
,(CASE WHEN (MAX(CAST(r.[PHASE_A] AS DATE)) >= MAX(CAST(r.[PHASE_B] AS DATE))) THEN 'PhB overlaps PhA' ELSE 'Pass' END) AS [PH-B_OL_PH-A]
,(CASE WHEN (MAX(CAST(r.[PHASE_A] AS DATE)) >= MAX(CAST(r.[PHASE_C] AS DATE))) THEN 'PhC overlaps PhA' ELSE 'Pass' END) AS [PH-C_OL_PH-A]
,(CASE WHEN (MAX(CAST(r.[PHASE_A] AS DATE)) >= MAX(CAST(r.[PHASE_D] AS DATE))) THEN 'PhD overlaps PhA' ELSE 'Pass' END) AS [PH-D_OL_PH-A]
,(CASE WHEN (MAX(CAST(r.[PHASE_B] AS DATE)) >= MAX(CAST(r.[PHASE_C] AS DATE))) THEN 'PhC overlaps PhB' ELSE 'Pass' END) AS [PH-C_OL_PH-B]
,(CASE WHEN (MAX(CAST(r.[PHASE_B] AS DATE)) >= MAX(CAST(r.[PHASE_D] AS DATE))) THEN 'PhD overlaps PhB' ELSE 'Pass' END) AS [PH-D_OL_PH-B]
,(CASE WHEN (MAX(CAST(r.[PHASE_C] AS DATE)) >= MAX(CAST(r.[PHASE_D] AS DATE))) THEN 'PhD overlaps PhC' ELSE 'Pass' END) AS [PH-D_OL_PH-C]
FROM [MyTable] AS r
GROUP BY r.[REC_ID] ,r.[ITEM_ID] ,r.[PHASE_NAME]
However, using this query, I get returned a "Pass" for every row. I think it's because MAX works on Rows rather than Columns.
Does anyone know the correct SQL code for comparing overlapping dates in such a scenario?
My environment in Microsoft SQL Server 2019.
Any suggestions are appreciated!