如何将具有开始日期和结束日期的现有 table 加入现有日历 table 以计算工作日

How to join an existing table that has starting date and closing date to the existing calendar table to calculate working days

如何将具有开始日期和结束日期的现有 table 加入现有日历 table 以计算工作日。

我的日历 table 看起来像这样 :-

dt  isweekday   isholiday   Y   FY  Q   M   D   DW  monthname   dayname W
1/1/2010 0:00   FALSE   FALSE   2010    2010    1   1   1   6   January Friday  1
1/2/2010 0:00   FALSE   FALSE   2010    2010    1   1   2   7   January Saturday    1
1/3/2010 0:00   TRUE    FALSE   2010    2010    1   1   3   1   January Sunday  2
1/4/2010 0:00   TRUE    FALSE   2010    2010    1   1   4   2   January Monday  2
1/5/2010 0:00   TRUE    FALSE   2010    2010    1   1   5   3   January Tuesday 2
1/6/2010 0:00   TRUE    FALSE   2010    2010    1   1   6   4   January Wednesday   2

和另一个包含开始日期和结束日期的 table 如下所示:-

orderid orderdate   ordercloseddate actionby
40978   4/15/2010 12:47 4/18/2010 14:47 tjjohn

是这样的吗?

select
  orderid,
  count(*)
from
  orders o
  join calendar c 
    on c.dt >= convert(date, c.orderdate) and
       c.dt <= convert(date, c.ordercloseddate) and
       c.isweekday = 'TRUE' and
       c.isholiday = 'FALSE'
group by
  o.orderid

不确定您的 'isholiday' 字段,希望它不是包含 TRUE / FALSE 字样的字符串。

这将给出特定订单的工作日期。

SELECT dt FROM calendar CROSS JOIN orders
 where DATEADD(day, DATEDIFF(Day, 0, dt), 0) between DATEADD(day, DATEDIFF(Day, 0, orderdate), 0) and DATEADD(day, DATEDIFF(Day, 0, ordercloseddate), 0)
   AND isweekday = 'TRUE'
   AND isholiday = 'FALSE'
   AND orderid = <anOrderId>

对于所有订单,

 SELECT orderid, count(dt) AS workingDays FROM calendar CROSS JOIN orders
 where DATEADD(day, DATEDIFF(Day, 0, dt), 0) between DATEADD(day, DATEDIFF(Day, 0, orderdate), 0) and DATEADD(day, DATEDIFF(Day, 0, ordercloseddate), 0) 
   AND isweekday = 'TRUE'
   AND isholiday = 'FALSE'
 GROUP BY orderid