Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL时间增量和。。。。我想我需要做自我加入吗?_Sql - Fatal编程技术网

SQL时间增量和。。。。我想我需要做自我加入吗?

SQL时间增量和。。。。我想我需要做自我加入吗?,sql,Sql,我的表有列 Group1 Group2 startdate enddate 该表的一般格式是这样的:group2具有唯一的ID,它们以批的形式聚集在一起,共享group1 ID,并且开始/结束日期对应于group2。有些数据可能看起来像 Group1 Group2 startdate enddate 1 51 20120101 1 23 20120201 2 54 20120101 2012020

我的表有列

 Group1  Group2  startdate enddate
该表的一般格式是这样的:group2具有唯一的ID,它们以批的形式聚集在一起,共享group1 ID,并且开始/结束日期对应于group2。有些数据可能看起来像

 Group1  Group2  startdate enddate
   1        51     20120101
   1        23     20120201
   2        54     20120101  20120201
   2        99     20120215
   3        21     20120201 20120301
日期不一定是第一个月,这样很容易

我需要一个查找特定事件的SELECT语句:当一个group2有一个结束日期,然后在不到一个月的时间内,另一个group2有一个相同Group1的开始日期。也就是说,客户取消并重新订阅不同的第2组,但相同的第1组。样本数据的“答案”是99


如果一个select语句不可能,请告诉我原因,并建议如何使用多个语句。

可能需要更多信息才能精确,但我感觉这是您需要自己解决其余问题的地方。这个解决方案有两个假设

SELECT  *
  FROM  MyTable t
 WHERE  enddate IS NULL
   AND  EXISTS(
                    SELECT  1
                      FROM  MyTable
                     WHERE  Group2 <> t.Group2
                       AND  Group1 = t.Group1
                       AND  enddate BETWEEN t.startdate AND DATEADD(month, -1, t.startdate)
                       AND  enddate IS NOT NULL
               )
Group1是您唯一的CustomerID,但在此表中不唯一。 你不在乎客户取消多久,直到他们重新订阅。 如果要使用单独的客户ID,则

将cutsomer ID添加到子列表的选择列表中 更改where子句以反映其用法 将其添加到join on子句中 要限制从取消到重新订阅的时间,需要进行稍微重要的编辑。如果你需要的话,我会试着把它寄出去


如果发布的答案不能解决问题,请发布更多信息,包括代码片段、表结构,以及更多关于它应该如何工作的想法。

是的,有一种自我连接的语法我弄错了。你的回答似乎澄清了这一点。
declare @table2 table(startdate datetime, enddate datetime, group1 int, group2 int)

insert into @table2 
select '20120101', null, 1, 51
UNION
select '20120101', null, 1, 23
UNION
select '20120101', '20120201', 2, 54
UNION
select '20120215', null, 2, 99
UNION
select '20120101', null, 3, 21

select a.group2 from @table2 a inner join @table2 b on a.group1 = b.group1 and b.enddate > DATEADD(mm, -1, a.startdate) and a.enddate is null
select      SD.Group1,
            MT.Group2,
            SD.startdate
from        MyTable MT
            join (
                select      Group1,
                            max(startdate) as startdate
                from        MyTable
                where       Group1 = 2
                group by    Group1
            ) SD on SD.Group1 = MT.Group1
                and SD.startdate = MT.startdate
                and SD.CustomerID = MT.CustomerID