MySQL - 查找某个月份的日期范围内的天数

时间:2014-04-11 13:13:54

标签: mysql

我有一张表格,显示人们在一个日期范围内工作的工作(最多不超过5天)。

是否可以按月分解日期范围的内容?

我的表格(简化)如下所示:

+---------------------+---------------------+--------------+
| datefrom            | dateto              | dailypayrate |
+---------------------+---------------------+--------------+
| 2014-05-05 00:00:00 | 2014-05-10 00:00:00 |        78.00 |
| 2014-04-07 00:00:00 | 2014-04-14 00:00:00 |        59.30 |
| 2014-02-10 00:00:00 | 2014-02-14 00:00:00 |        82.66 |
| 2014-04-28 00:00:00 | 2014-05-02 00:00:00 |        91.00 |<-- !
| 2014-01-28 00:00:00 | 2014-01-31 00:00:00 |        65.00 |
+---------------------+---------------------+--------------+

我想显示某个月内每行付费的总额,例如在4月份的第4行的情况下,它将显示273,即91的每日工资乘以4月份工作的3天(即使该行显示为5天)。

2 个答案:

答案 0 :(得分:1)

嗯,我不知道这是否是一个完整的解决方案,但这是一个开始......

SELECT *
     , (DATEDIFF(LEAST(LAST_DAY(datefrom),dateto),datefrom)+1)*dailypayrate x 
  FROM  
     my_table;
+---------------------+---------------------+--------------+--------+
| datefrom            | dateto              | dailypayrate | x      |
+---------------------+---------------------+--------------+--------+
| 2014-01-28 00:00:00 | 2014-01-31 00:00:00 |        65.00 | 260.00 |
| 2014-02-10 00:00:00 | 2014-02-14 00:00:00 |        82.66 | 413.30 |
| 2014-04-07 00:00:00 | 2014-04-14 00:00:00 |        59.30 | 474.40 |
| 2014-04-28 00:00:00 | 2014-05-02 00:00:00 |        91.00 | 273.00 |
| 2014-05-05 00:00:00 | 2014-05-10 00:00:00 |        78.00 | 468.00 |
+---------------------+---------------------+--------------+--------+

http://sqlfiddle.com/#!2/7c1cbb/1

答案 1 :(得分:1)

你可以在SQL中做你想做的事,但它不是很可爱。很容易计算出日期范围不包括月份变化的行(WHERE MONTH(timefrom)= MONTH(timeto))。只要像草莓一样做一个DATEDIFF。

SELECT 
        MONTH(datefrom) as month_number, 
        DATEDIFF(dateto, datefrom) as days_worked, 
        DATEDIFF(dateto, datefrom)*dailypayrate as salary
FROM my_table
WHERE MONTH(datefrom) = MONTH(dateto)

对于包含月份更改的日期范围,我们需要将这些行分成两行:一行将计入MONTH(timefrom),另一行计入MONTH(timeto)。这是MONTH(timeto),另一个只是减法。

SELECT 
        MONTH(dateto) as month_number, 
        MINUTE(dateto)/(60*24) + HOUR(dateto)/24 + DAY(dateto)-1 as days_worked, 
        (MINUTE(dateto)/(60*24) + HOUR(dateto)/24 + DAY(dateto)-1)*dailypayrate as salary
FROM my_table
WHERE MONTH(datefrom) != MONTH(dateto)

然后我们UNION这3个查询,按month_number分组,它应该给出正确的数字。

http://sqlfiddle.com/#!2/120766/2