我在使用包含重复记录的Union的CTE生成结果集。如下图所示:
查询是:
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)
)
现在我试图从这个结果集中删除重复的结果。所以最后结果集应该只有2行。所以它应该如下所示:
任何帮助将不胜感激。感谢。
有关详细信息,请使用以下CTE生成第一个结果集
答案 0 :(得分:1)
您可以使用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
)
或 - 如果您在此表中没有主键:
WITH CTE AS
(
SELECT t.*, cnt = COUNT(*) OVER (PARTITION BY StartTime, EndTime)
FROM dbo.TableName t
)
SELECT StartTime, EndTime
FROM CTE
WHERE cnt = 1