每行都有DateEff
和DateExp
。让我说我返回5行。我需要检查第一行中的DateEff
,看它是否位于第二,第三,第四和第五行的DateEff
和DateExp
之间,依此类推。我需要检查每个DateEff
,以确保它不在任何行DateEff
和DateExp
之间。
以下是数据外观的示例。如您所见,第3行DateEff
是(2013-03-30),它位于第4行DateEff
和DateExp
以及第5行DateEff
和“DateExp”之间。
表
rowid DateEff DateExp
1 1969-01-01 2012-09-30
2 2012-10-01 2012-12-31
3 2013-03-30 2014-12-31
4 2013-01-01 2015-02-10
5 2013-01-01 2999-01-01
结果看起来像这样
Prob Id Problem Date Affected Id Aff Date Range
3 2013-03-30 4 2013-01-01 - 2015-02-10
3 2013-03-30 5 2013-01-01 - 2999-01-01
答案 0 :(得分:0)
将表连接到自身以返回重叠的行对:
Select a.RowID, a.DateEff as ProblemDate
, b.RowID as OverlapID, b.DateEff as OverlapStart, b.DateExp as OverlapEnd
from MyTable a
left join MyTable b
on a.RowID <> b.RowID
and a.DateEff <= b.DateExp
and a.DateEff >= b.DateEff
答案 1 :(得分:0)
我认为这应该适合你:
string
使用您的样本数据,结果如下:
select
[Prob Id] = t.rowid,
[Problem Date] = t.DateEff,
[Affected Id] = a.rowid,
[Aff Date Range] = concat(a.DateEff,' - ',a.DateExp)
from tbl t -- your table is called tbl
outer apply
(
select *
from tbl -- your table is called tbl
where t.DateEff between dateeff and DateExp and rowid > t.rowid
) a
where a.DateEff is not null
order by t.rowid, t.DateEff;
要从示例中获取确切输出(第4行除外),请将应用中的条件更改为Prob Id Problem Date Affected Id Aff Date Range
3 2013-03-30 4 2013-01-01 - 2015-02-10
3 2013-03-30 5 2013-01-01 - 2999-01-01
4 2013-01-01 5 2013-01-01 - 2999-01-01
。输出将是:
t.DateEff > dateeff and t.DateEff < DateExp and rowid > t.rowid