MYSQL如何排除2个不同日期之间的工作日

时间:2019-02-26 02:37:36

标签: mysql sql

我需要计算该日期之间的天数。我有2个不同的日期,date1名称为vcr_date和date2名称为bbp_date。例如,vcr_date ='2019-01-01'是星期二,bbp_date ='2019-01-07'是星期一,其间的天数是6天。如果我想排除星期五和星期六,则计数为4天。如何在MYSQL中做到这一点?

样品表:

CREATE TABLE `datatest` (
  `vcr_date` date default NULL,
  `bbp_date` date default NULL,
  `comp_name` varchar(50) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='InnoDB free: 102400 kB; InnoDB free: 99328 kB; InnoDB free: ';
#----------------------------
# Records for table datatest
#----------------------------

insert  into datatest values 
('2019-01-06', '2019-01-02', 'J.O.E SUPPLIER SDN BHD'), 
('2019-01-05', '2019-01-03', 'AURAJUBLI SDN BHD'), 
('2019-01-14', '2019-01-04', 'NEW MT CENTURY SDN. BHD.'), 
('2019-01-25', '2019-01-05', 'KMT SUPPLY SDN BHD'), 
('2019-01-10', '2019-01-06', 'SASHWIN SDN. BHD.'), 
('2019-01-17', '2019-01-07', 'J.O.E SUPPLIER SDN BHD');

SQL计算天数:

SELECT *,datediff(vcr_date,bbp_date) as daycount
FROM datatest

1 个答案:

答案 0 :(得分:0)

我在下面的sql server中尝试过,希望对您有所帮助。

declare @start_dt date,
        @end_dt date
set @start_dt = '20190101'
set @end_dt = '20190107'

;with cte
AS
(
select @start_dt AS dt
UNION ALL
SELECT dateadd(day,1,dt)
FROM cte
WHERE dt < DATEADD(DAY,DATEDIFF(DAY,0,@end_dt),0) and datename(dw,dateadd(day,1,dt)) not in('Monday','Saturday')
)
select count(*)
from cte