如何编写SQL语句?

时间:2011-04-25 02:35:50

标签: sql

我想知道SQL语句来解决以下问题。我在这里遇到了一些问题。

SupplierID  ContractStart   ContractEnd         

20          1/1/2010        1/3/2010
24          12/12/2008      12/1/2009
31          13/1/2008       13/2/2008
20          13/1/2008       13/2/2008
24          11/11/2007      11/12/2010
31          12/12/2008      1/1/2009

请在此表中标明重叠合同的供应商ID。

3 个答案:

答案 0 :(得分:1)

如果您的表格为t,则应执行此操作:

select a.supplierid, b.supplierid
from t a, t b
where ((b.contractstart<a.contractend and b.contractend>a.contractend)
    or (a.contractstart<b.contractstart and a.contractend>b.contractstart))
    and a.supplierid<b.supplierid -- strict so you don't get doubles

编辑:这是假设您的重复ID是拼写错误。

答案 1 :(得分:0)

SELECT a.sid 
FROM contracts a, contracts b
WHERE a.sid == b.sid
AND a.start < b.start
AND a.end > b.start;

答案 2 :(得分:0)

如果您希望按供应商ID识别重叠,这应该有效:

仅供参考我使用mm / dd / yyyy

declare @contract table ( SupplierID int, ContractStart datetime, ContractEnd datetime)

insert into @contract
select 20, '1/1/2010', '3/1/2010'
union all
select 24 , '12/12/2008', '1/12/2009'
union all
select 31, '1/13/2008 ', '2/13/2008'
union all
select 20, '1/13/2008', '2/13/2008'
union all
select 24, '11/11/2007 ', '12/11/2010'
union all
select 31, '12/12/2008 ', '1/1/2009'

SELECT a.supplierid, 
       a.contractstart, 
       a.contractend, 
       b.contractstart, 
       b.contractend 
FROM   @Contract a 
       INNER JOIN @Contract b 
         ON b.supplierid = a.supplierid 
WHERE  ( b.contractstart < a.contractend ) 
       AND ( b.contractend > a.contractstart ) 
       AND ( b.contractstart != a.contractstart --Ignore overlap with self
             AND b.contractend != a.contractend ) 
       AND b.contractstart > a.contractstart -- No Duplicates