Below is the method which is working fine, but how do I convert it and use it directly inside select statement to get the desired results.
SET GLOBAL log_bin_trust_function_creators=1;
DROP FUNCTION IF EXISTS DayCount;
DELIMITER |
CREATE FUNCTION DayCount( d1 DATE, d2 DATE, daynum SMALLINT ) RETURNS INT
BEGIN
DECLARE days INT DEFAULT 0;
IF D1 IS NOT NULL AND D2 IS NOT NULL THEN
WHILE D1 <= d2 DO
BEGIN
IF DAYOFWEEK(d1) = daynum THEN
SET days=days+1;
END IF;
SET d1 = ADDDATE(d1, INTERVAL 1 DAY);
END;
END WHILE;
END IF;
RETURN days;
END;
|
DELIMITER;
SELECT (daycount('2017-02-05','2017-02-20',7)) + (daycount('2017-02-05','2017-02-20',1)) AS 'Weekends';
For above query, I need a way to pass 7 & 1 dynamically to be able to pass non-workdays as well and remove those days from main query to calculate resolution and response time, but no function at all, direct select statement way of doing it.
UPDATED:
I have a query below, where I'm calculating time between closeDate and edate where I need to exclude non-workdays, the non-workday list is dynamic, it could be from 1 to 7 (Sunday to Saturday), my requirement is to exclude non-workdays and calculate average via mysql query itself instead of manipulating things later on via PHP:
SELECT `complains`.`id`,
DATE (edate) AS _date,
AVG((UNIX_TIMESTAMP(closeDate) - UNIX_TIMESTAMP(edate))) AS _seconds,
COUNT(*) AS totalCases
FROM `complains`
WHERE (
(`complains`.`govt_id` = '22')
AND (
`complains`.`edate` BETWEEN DATE ('2016-01-01')
AND DATE ('2017-01-01')
)
)
AND (`complains`.`status` = 2)
GROUP BY `_date`
ORDER BY `_date`
So workdays must be excluded between different fields i.e closeDate and edate, where edate is entrydate of a case. I'm basically calculating average resolution time of cases.
SQL Fiddle link to sql fiddle