在 SQL 中查找重叠的价格有效期

Find overlapping price validity dates in SQL

我面临着一个挑战,我无法以我有限的 SQL 技能掌握。我希望你能帮助我。鉴于我有一个 table,其商品价格在指定时间跨度内对特殊客户有效。

因为人们有时在输入一个时间跨度的新价格之前不会考虑,所以我必须找出 Item No 和 Customer No 组合的重叠时间跨度。我只需要找出是否存在是重叠发生,而不是重叠发生时。

我有一个 table CustomerPrices,其数据如下:

Item No   Customer No     Valid from    Valid to      Price
12345     55544           01.01.2016    31.05.2016    5,66
12345     55544           01.03.2017    01.06.2017    4,55
12345     55544           01.02.2017    01.07.2017    6,41

你能给我指明正确的方向吗?

致以最诚挚的问候,谢谢!

select 
    itemno, 
    custno,
    validfrom, 
    validto, 
    price 
from 
    CustomerPrices a
where 
    exists (
        select 1 
        from CustomerPrices b 
        where 
            a.itemno = b.itemno 
            and a.custno = b.custno
            and ((a.validfrom between b.validfrom and b.validto) 
              or (a.validto between b.validfrom and b.validto)) 
    )

您可以将日期类型的条目转换为整数表示形式(参见 here)。这将使您可以更轻松地比较日期条目。

如果您只需要 customer/item 对重叠,则:

select distinct custno, itemno
from customerprices cp
where exists (select 1
              from customerprices cp2
              where cp2.custno = cp.custno and cp2.itemno = cp.itemno and
                    cp2.validfrom <= cp.validto and
                    cp2.validto >= cp.validto and
                    (cp2.validfrom <> cp.validfrom or cp2.validto <> cp.validto)
             );

这是什么逻辑?首先,它假设时序上没有完整的重复项。其次,它检查是否有任何重叠——包括结束段。这应该可以处理任何重叠 (ABBA, ABAB)。

不确定,您正在寻找什么输出?解释输出。

IT return 最后一行,因为它的有效来源与前一行有效重叠。

declare @t table(id int identity(1,1),ItemNo int,CustomerNo int
,Validfrom date,Validto date,Price int)
insert into @t VALUES
(12345,55544, '2016-01-01','2016-05-31',566)
,(12345,55544,'2017-03-01','2017-06-01',455)
,(12345,55544,'2017-02-01','2017-07-01',641)
select t1.*

from @t t
inner join @t t1
 on t.ItemNo=t1.ItemNo
and t.CustomerNo=t1.CustomerNo
where 
 (t1.Validfrom<t.Validto)
 and t1.id-t.id=1