0

I have a result set in generated as CTE using Union that contains duplicate records. as in image below:

enter image description here

And the query is:

WITH CTE  (StartTime ,EndTime )
AS
(
SELECT StartTime ,EndTime, Null as Exclude, SupplierId FROM cms.TimeSlotMaster
WHERE Monday = 1 AND SupplierID IS NULL

UNION

SELECT StartTime ,EndTime FROM cms.TimeSlotOverRider
WHERE SupplierID IS NULL
AND StartDate <= cast(GETDATE() as DATE) AND EndDate >= cast(GETDATE() as DATE)
)

Now I am trying to remove the duplicate results from this result set at all. So finally the results set should be only 2 rows. So it should look like below:

enter image description here

Any help would be appreciated. Thanks.

For more information the first result set is generated using below CTE

Language Lassi
  • 2,520
  • 21
  • 24

1 Answers1

1

You can use NOT EXISTS:

SELECT t.*
FROM dbo.TableName t
WHERE NOT EXISTS
(
    SELECT 1 FROM dbo.TableName t2
    WHERE t. ID <> t2.ID
     AND  t.StartTime = t2.StartTime 
     AND  t.EndTime   = t2.EndTime
)

or - if you don't have a primary key in this table:

WITH CTE AS
(
    SELECT t.*, cnt = COUNT(*) OVER (PARTITION BY StartTime, EndTime)
    FROM dbo.TableName t
)
SELECT StartTime, EndTime 
FROM CTE 
WHERE cnt = 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939