【问题标题】:Selects between values for multiple rows在多行的值之间进行选择
【发布时间】:2014-08-26 19:26:33
【问题描述】:

我有一张桌子 X:

id      startDt     EndDt
---------------------------------------------------------------------
1       1/1/1900    9/30/2012
2       10/2/2012   10/4/2012
3       10/3/2012   10/7/2012
4       11/5/2012   11/15/2012

我需要编写一个查询,从另一个表 Y 中选择所有行,其中 EventDate 位于 X 的每个开始日期和结束日期之间。

也就是说,结果集应该是 Y 中所有记录的并集,其中日期在每行的开始日期和结束日期之间。 (1900 年 1 月 1 日至 2012 年 9 月 30 日之间的所有日期 + 2012 年 10 月 2 日至 2012 年 10 月 7 日之间的所有日期 + 2012 年 11 月 5 日至 2012 年 11 月 15 日之间的所有日期)

我确实有一个执行此操作的工作程序,但解决方案是使用循环,如果可能,我想在查询中执行此操作。

谢谢!

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    对于至少在 1 个开始日期和结束日期之间的日期

    select * from y t1
    where exists (
        select 1 from x t2 where
        t1.eventdate between t2.startDt and t2.endDt 
    )
    

    如果您只想要每个开始和结束之间的日期

    select * from y t1
    where not exists (
        select 1 from x t2 where
        t1.eventdate not between t2.startDt and t2.endDt 
    )
    

    【讨论】:

      【解决方案2】:

      FuzzyTree 的答案可能是最快和最好的,但我想我会分享一个替代方案。也许唯一的优势是可读性。

      Select *
      From Y y1
      Where 
          (Select Count(*) From x) =
              (  Select Count(*) 
                 From x1
                 Where y1.date Between x1.StartDate And x1.EndDate
              )
      

      【讨论】:

        猜你喜欢
        • 2018-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多