SQL 查询从两个日期列中获取工作日
SQL query get business days from two date columns
我有一个包含两列的 sql table。一列名为 dateUpdated,另一列名为 dateReported。我希望创建第三列,其中包含每一行的 dateUpdated 和 dateReported 之间的工作日整数值。 dateUpdated 将始终是 dateReported 值之后或之上的日期。例如,table 可能看起来像:
DATE UPDATED Date Reported
2015-06-23 2015-06-02
2015-06-05 2015-06-04
2015-06-23 2015-06-15
2015-06-17 2015-06-04
2015-06-23 2015-06-27
2015-06-23 2015-06-04
2015-06-08 2015-06-04
第三列应该是每行两列之间的工作日数。我现在的 sql 看起来像这样
select date(time_of_update) as updated,
rep.date_reported as dateReported
from history hist left join reports rep
on hist.name = rep.name
left join calendar cal
on rep.date_reported = cal.calendar_date;
我的日历 table 有一个包含所有日期的列以及一个标记它们是否为工作日的关联列。例如,我可以 运行 类似
select sum(is_business_day) from calendar where
calendar_date between '2015-06-02' and '2015-06-23';
我会得到 16 天。我想知道如何合并这两个以获得上述两个列以及第三个列。
子查询是 acceptable,如果这是唯一的方法的话。谢谢!
如果 dt_tbl
是你的 table dateUpdated 和 dateReported,而 calendar
是你的 table 日历日期,那么这样做:
select
a.dateUpdated
, a.dateReported
, sum(is_business_day) num_business_days
from
dt_tbl a
left join
calendar c on c.calendar_date between a.dateReported and a.dateUpdated
group by
a.dateUpdated
, a.dateReported
我有一个包含两列的 sql table。一列名为 dateUpdated,另一列名为 dateReported。我希望创建第三列,其中包含每一行的 dateUpdated 和 dateReported 之间的工作日整数值。 dateUpdated 将始终是 dateReported 值之后或之上的日期。例如,table 可能看起来像:
DATE UPDATED Date Reported
2015-06-23 2015-06-02
2015-06-05 2015-06-04
2015-06-23 2015-06-15
2015-06-17 2015-06-04
2015-06-23 2015-06-27
2015-06-23 2015-06-04
2015-06-08 2015-06-04
第三列应该是每行两列之间的工作日数。我现在的 sql 看起来像这样
select date(time_of_update) as updated,
rep.date_reported as dateReported
from history hist left join reports rep
on hist.name = rep.name
left join calendar cal
on rep.date_reported = cal.calendar_date;
我的日历 table 有一个包含所有日期的列以及一个标记它们是否为工作日的关联列。例如,我可以 运行 类似
select sum(is_business_day) from calendar where
calendar_date between '2015-06-02' and '2015-06-23';
我会得到 16 天。我想知道如何合并这两个以获得上述两个列以及第三个列。
子查询是 acceptable,如果这是唯一的方法的话。谢谢!
如果 dt_tbl
是你的 table dateUpdated 和 dateReported,而 calendar
是你的 table 日历日期,那么这样做:
select
a.dateUpdated
, a.dateReported
, sum(is_business_day) num_business_days
from
dt_tbl a
left join
calendar c on c.calendar_date between a.dateReported and a.dateUpdated
group by
a.dateUpdated
, a.dateReported