在SQL

时间:2017-05-04 18:09:50

标签: sql sql-server date overlap timespan

我面临的挑战是我无法掌握我有限的SQL技能。我希望你能帮助我。鉴于我有一个项目价格的表格,对于指定时间跨度的特殊客户有效。

因为人们有时在进入新的价格之前没想到时间跨度,我必须找出,对于项目编号和客户编号的组合存在重叠的时间跨度,我只需要找出如果存在重叠正在进行,而不是重叠发生时。

我有一个表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

你能指点我正确的方向吗?

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

4 个答案:

答案 0 :(得分:0)

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)) 
    )

答案 1 :(得分:0)

您可以将日期类型的条目转换为整数表示(请参阅here)。这样您就可以更轻松地比较日期条目。

答案 2 :(得分:0)

如果您只需要重叠的客户/项目对,那么:

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)。

答案 3 :(得分:0)

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

IT返回最后一行,因为它的有效from与前一行validto重叠。

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