我有一个具有以下结构的表:
ProductId | ValidFrom | ValidTo | Price
然而,似乎我对同一个ProductId有一些重叠的ValidFrom和ValidTo Dates。
如何创建输出的查询:
ProductId | Overlapping Dates
答案 0 :(得分:2)
SELECT DISTINCT ProductId, a.ValidFrom , b.ValidTo FROM
yourTable a
JOIN yourTable b ON a. ValidFrom BETWEEN b.ValidFrom AND b.ValidTo
OR a. ValidTo BETWEEN b.ValidFrom AND b.ValidTo
答案 1 :(得分:0)
好的,我使用您的回复到达那里。 但是我根据productId和日期为每一行创建了一个Key。 我只显示不相同的行。
SELECT DISTINCT ProductId, a.ValidFrom , b.ValidTo FROM
yourTable a
JOIN yourTable b ON a. ValidFrom BETWEEN b.ValidFrom AND b.ValidTo
OR a. ValidTo BETWEEN b.ValidFrom AND b.ValidTo
AND
(cast(T1.ProductId as nvarchar(50) + Cast(T1.ValidFrom as nvarchar(50)) + Cast(T1.ValidTo as nvarchar(50)))
<>
(cast(T2.ProductId as nvarchar(50) + Cast(T2.ValidFrom as nvarchar(50)) + Cast(T2.ValidTo as nvarchar(50)))