【问题标题】:DATEDIFF() Excluding Marked DaysDATEDIFF() 不包括标记日
【发布时间】:2017-09-22 18:48:58
【问题描述】:

我想看看两个日期之间有多少天,不包括取决于另一个表中规定的值的某些日期。

表1

ID    in_date      out_date
001   01/01/2017   01/05/2017
002   01/03/2017   01/05/2017

例如:

SELECT 
   id
  ,datediff(dd, t1.in_date, t1.out_date) as diff
FROM table1 t1

会带来

ID    diff
001   4
002   2

但是假设我有另一张桌子:

表2

date         use
01/01/2017   Y
01/02/2017   N
01/03/2017   N
01/04/2017   Y
01/05/2017   Y

我想查看use 列下有 Y 的日期之间的日期差异。

所以连接表1和2时的结果应该是:

ID    diff
001   3
002   2
  • 这是一个案例陈述吗?
  • 我将如何在表一中的上述示例中使用?我会根据日期加入吗?

【问题讨论】:

  • datediff(月,in_date,out_date)
  • table2 总是 是否会在table1 中的最小和最大日期之间的每个 日期包含一个条目?

标签: sql sql-server tsql


【解决方案1】:

您可以根据日期使用left join

select t.id, count(t2.date) as diff
from table1 as t
  left join table2 as t2
    on t2.date >= t.in_date
   and t2.date <= t.out_date
   and t2.[use] = 'Y'
group by t.id

rextester 演示:http://rextester.com/XNX74966

返回:

+-----+------+
| id  | diff |
+-----+------+
| 001 |    3 |
| 002 |    2 |
+-----+------+

【讨论】:

    【解决方案2】:

    我会想到这样的事情:

    SELECT t1.id,
           t2.cnt as diff
    FROM table1 t1 outer apply
         (select count(*) as cnt
          from table2 t2
          where t2.date >= t1.in_date and t2.date <= t1.out_date and t2.use = 'Y'
         ) t2;
    

    即计算匹配天数并省去datediff()

    【讨论】:

      【解决方案3】:

      我猜用例是: - 确定两个给定日期之间的工作日期数。 即 table2 包含所有假期。 如果我的假设是正确的,那么最好只在 table2 中存储假期和周末。即表 2 中不需要 [use]='N' 的条目。 在这个假设下,我会这样做:

       Create function dbo.GetHolidayCount(@indate datetime, @outdate datetime)
          returns int as
          Begin
          Declare @cnt int = 0
          Select @cnt = count(*) from table2 where [date] >= @indate and [date] <= @outdate and [use]='N';
          return @cnt
          End
      

      然后发出以下查询。

         SELECT 
         id, 
        ,datediff(dd, t1.in_date, t1.out_date) + 1 - dbo.GetHolidayCount(t1.in_date, t1.out_date) as diff
      FROM table1 t1
      

      我将结果加 1,因为 01/01/2017 和 01/05/2017 之间的 datediff 将返回 4;但根据您的要求,您需要 5 个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 2017-07-30
        • 2011-11-15
        • 2021-12-27
        相关资源
        最近更新 更多