3

我希望从我从 MySQL 数据库中检索到的数据中计算工作日的工作天数和周末工作的天数。

数据库中的时间格式如下:2013-07-01 07:00

这是我到目前为止所拥有的:

function isWeekend($date) {
    $check = date("w", strtotime($date));
        if ($check == 6 || $check == 0) {
            return 1;
        }
        else {
            return 0;
        }
}

$query = mysql_query ("SELECT date from jobcards");

while ($row = mysql_fetch_assoc($query)) {
  $date = $row['date'];
  $date_check= isWeekend($date);

  if ($date_check == 1) {
  ++$weekend;
  }
  else {
  ++$workday;
  }

}

我需要找到一种方法来计算使用 mysql 的天数,有没有这样的方法或更优雅的方法来改进 PHP 代码?

此外,如果我在数据库中有多个记录具有相同的日期范围但不同的时间示例:2013-07-01 07:00 和 2013-07-01 07:30 它将被计为两个工作日,我将如何防止这种情况发生?

谢谢。

4

4 回答 4

9

查看WEEKDAY函数,并将其与周日/周六(分别)的 6/5 进行比较

您的 SQL 将类似于:

SELECT SUM(IF(WEEKDAY(date) >= 5, 1, 0) AS WeekendCount,
       SUM(IF(WEEKDAY(date) < 5, 1, 0) AS WeekdayCount
FROM jobcards

There is a similar answer here: MySQL Weekday/Weekend count - Part II

Fixed the ) of the IF being placed in the wrong place

于 2013-07-01T09:00:50.827 回答
1
SELECT SUM(IF(DAYOFWEEK(date) BETWEEN 2 AND 6,1,0) AS weekdays,
SUM(IF(DAYOFWEEK(date) NOT BETWEEN 2 AND 6,1,0) AS weekends,
FROM jobcards
于 2013-07-01T09:01:57.427 回答
0
SELECT date, 
sum(date) total, 
sum(if(date_format(date,'%w') between 1 and 5),1,0) weekday,
sum(date) - sum(if(date_format(date,'%w') between 1 and 5),1,0) weekend
from jobcards
于 2013-07-01T09:03:44.940 回答
0

If you want to do this in SQL, you can solve the timestamp problem using the MySQL DATE() function, and the DAYOFWEEK() function to count your weekdays/weekends (Note that the day numbers for Sat/Sun are 7/1 in MySQL and not 6/0 as in PHP). So to count the distinct weekday entries it would look something like:

SELECT COUNT(*) FROM jobcards WHERE DAYOFWEEK(DATE(jobcards.date)) BETWEEN 2 AND 6;
于 2013-07-01T09:12:21.963 回答