MySQL查询计算同一行中两个单元格之间的工作日

时间:2013-03-11 13:03:51

标签: mysql datetime date-arithmetic

我有下表:

CREATE TABLE `document` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `systemReceivedTime` BIGINT(20) NOT NULL DEFAULT '0',
    `finishTime` BIGINT(20) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`)
)

一行:

systemReceivedTime 1360747818002 // > 2013-02-13 11:30:18
finishTime         1362995961805 // > 2013-03-11 11:59:22

我需要的是一种计算两个日期之间工作日数的方法。

正确显示日期使用以下选择:

from_unixtime(systemreceivedtime/1000) ,
if(finishtime=0,null,from_unixtime(finishtime/1000))

2 个答案:

答案 0 :(得分:0)

SELECT 5 * (DATEDIFF(FROM_UNIXTIME(finishTime/1000), FROM_UNIXTIME(systemReceivedTime/1000)) DIV 7) + MID('0123455501234445012333450122234501101234000123450', 7 * WEEKDAY(FROM_UNIXTIME(systemReceivedTime/1000)) + WEEKDAY(FROM_UNIXTIME(finishTime/1000)) + 1, 1)x FROM document;

答案 1 :(得分:0)

我有变量的解决方案。你可以将mor公式放在一起,但我认为它更具可读性。

SELECT
    calc.id,
    calc.work_dates
FROM
    (
        SELECT
            d.id,
            @from :=from_unixtime(d.systemreceivedtime/1000)        AS dfrom,
            @to := from_unixtime(d.finishtime/1000)                 AS dto,
            -- Caclulate the Diffrent between both dates
            @ddiff := DATEDIFF(@to, @from)          AS ddiff,
            -- get the weekday of the startdate
            @wd := WEEKDAY(@from)                       AS weekdays,
            -- calculate how many days are from start of week until enddate
            @d1 := @ddiff + @wd                         AS days_from_week_start,
            -- calculate how many full week this is
            @fullweeks := @d1 DIV 7                     AS full_weeeks,
            -- calculate how many workdays are not in a fullweek
            @restdays := LEAST(MOD(@d1, 7), 5)      As rest_working_days,
            -- Weeks * 5 Workdays + rest_workdays - days_from_week_start
            @fullweeks * 5 + @restdays - @wd            AS work_dates
        FROM
            document AS d
    ) AS calc