SQL Server在表一和表二中的日期条件中获取一个表中的ID

时间:2018-05-31 20:35:50

标签: sql sql-server

我在使用满足以下条件的表A中的ID时遇到问题(我尝试了很多不同的东西并查看了各种SO答案,但无法使其正常工作。我调查了OVER(PARTITION BY TABLE_B.calendar)):< / p>

  1. 在startDate(TABLE_A)之后10天或之后,第一个calendarDay(TABLE_B)上的Open(TABLE_B)应该等于1。

  2. endDate(TABLE_A)应该等于1)中找到的日期(即满足条件的相应id的calendarDay)。

  3. 示例数据:

    TABLE_A

        +----+------------+------------+
        | id | startDate  | endDate    |
        +----+------------+------------+
        | 1  | 2011-02-14 | 2011-03-14 |
        | 2  | 2012-12-19 | 2013-01-20 |
        | 3  | 2014-12-19 | 2015-01-21 |
        +----+------------+------------+
    

    表-B

        +-------------+------+
        | calendarDay | open |
        +-------------+------+
        | 2011-03-14  | 1    |
        | 2011-03-16  | 0    |
        | 2013-01-20  | 1    |
        | 2013-01-21  | 1    |
        | 2015-01-21  | 0    |
        | 2015-01-22  | 1    |
        +-------------+------+
    

    期望的结果:

        +----+------------+------------+
        | id | startDate  | endDate    |
        +----+------------+------------+
        | 1  | 2011-02-14 | 2011-03-14 |
        | 2  | 2012-12-19 | 2013-01-20 |
        +----+------------+------------+
    

4 个答案:

答案 0 :(得分:1)

您可以使用CTE首先获得第一个日历日:

with cteId(n, id, [open])
as (
    select ROW_NUMBER() over (partition by a.id order by b.calendarDay) n, a.id, b.[open]
    from #TABLE_A a
    inner join #TABLE_B b on b.calendarDay >= DATEADD(day, 10, a.startDate)
)

...然后加入TABLE_A

select a.*
from #TABLE_A a
inner join cteId c on a.id = c.id
where c.n = 1 and c.[open] = 1

答案 1 :(得分:1)

我想你想要:

select a.*
from a cross apply
     (select top (1) b.*
      from b
      where b.open = 1 and b.calendarDate >= dateadd(day, 10, a.startdate)
      order by b.calendarDate asc
     ) b
where b.calendarDate = a.endDate

答案 2 :(得分:1)

您可以尝试此查询。

使用Exists

select a.* 
from TABLE_A as a
where exists( 
              SELECT 1 
              FROM TABLE_B b
              where
              a.startDate <= DateAdd(day, 10, b.calendarDay) and b.[open] = 1
            ) 
and exists( 
             SELECT 1 
             FROM TABLE_B b
             where
             a.endDate  = b.calendarDay  and b.[open] = 1
            ) 

sqlfiddle:http://sqlfiddle.com/#!18/320111/15

另一种方法可以尝试使用join

select a.* 
from TABLE_A as a 
INNER JOIN 
(
  SELECT b.*,DateAdd(day, 10, b.calendarDay) addDay
  FROM TABLE_B b
  where b.[open] = 1
) b on a.startDate <= addDay and a.endDate = b.calendarDay

sqlfiddle:http://sqlfiddle.com/#!18/320111/19

答案 3 :(得分:0)

您可以在此处使用“存在”来查找匹配值

Select  * 
From    Table_A a
Where   Exists (
            Select  1
            From    Table_B b
            Where   b.[open] = 1
            And     b.calendarDay >= DateAdd(dd, 10, a.endDate)
            And     b.calendarDay = a.endDate)
        )