php - 合并顺序日期

标签 php mysql

我的表中有以下数据

table data

根据 shift_id 我想合并类次日期。

简而言之,我想要以下输出:

**output format : FromDate To ToDate (Shift_id)**

2012-12-01 To 2012-12-02 (2)

2012-12-03 (1)

2012-12-04 (2)

2012-12-18 To 2012-12-20 (1)

2012-12-21 To 2012-12-22 (2)

2012-12-23 To 2012-12-24 (1)

2012-12-25 To 2012-12-30 (2)

我尝试了几件事,但没有成功。任何人请帮助/指导我解决这个问题。

这段代码是我写的

    while($row_shift = mysql_fetch_object($result_shift)) {
    $new_date = $row_shift->shift_date;
    $new_shift = $row_shift->shift_id;
    if($new_shift !== $old_shift) {
        $shift_name = $new_shift;
        $shift_date_1 =  date('D d M',strtotime($new_date))." (".$shift_name.")";               
    } else {
        $shift_name = $old_shift;
        $shift_date_1 =  date('D d M',strtotime($old_date))." (".$shift_name.")";
        $diff = abs(floor( (strtotime($new_date) - strtotime($old_date)) / 3600 / 24));
        if($diff == 1) {                    
            $to_part = ' To ';
            $shift_date_2 = date('D d M',strtotime($new_date))." (".$shift_name.")";

        } else {
            $to_part = ' To ';
            $shift_date_2 = date('D d M',strtotime($old_date))." (".$shift_name.")";    
        }
    }

    $s_d_2 = $to_part.$shift_date_2;

    $shift_date[] = $shift_date_1.$s_d_2;

    $old_date = $row_shift->shift_date;
    $old_shift = $row_shift->shift_id;

}
echo implode("<br/>", $shift_date);

这段代码的输出是

Output : 
Sat 01 Dec (2)
Sat 01 Dec (2) To Sun 02 Dec (2)
Mon 03 Dec (1)Sun 02 Dec (2)
Tue 04 Dec (2)Sun 02 Dec (2)
Tue 18 Dec (1)Sun 02 Dec (2)
Tue 18 Dec (1) To Wed 19 Dec (1)
Wed 19 Dec (1) To Thu 20 Dec (1)
Fri 21 Dec (2)Thu 20 Dec (1)
Fri 21 Dec (2) To Sat 22 Dec (2)
Sun 23 Dec (1)Sat 22 Dec (2)
Sun 23 Dec (1) To Mon 24 Dec (1)
Tue 25 Dec (2)Mon 24 Dec (1)
Tue 25 Dec (2) To Wed 26 Dec (2)
Wed 26 Dec (2) To Thu 27 Dec (2)
Thu 27 Dec (2) To Fri 28 Dec (2)
Fri 28 Dec (2) To Sat 29 Dec (2)
Sat 29 Dec (2) To Sun 30 Dec (2)

谢谢。

最佳答案

这是一个SQLFiddle demo

select min(shift_date) start_data,max(shift_date) end_date,
          min(Shift_id) Shift_id
from
(
select t.*,if(shift_id<>@CurShift,@i:=@i+1,@i) Group_num,
       @CurShift:=shift_id 
from t, (select @CurShift:=0,@i:=0) t1 
order by shift_date
 ) b

group by Group_num
order by Group_num

关于php - 合并顺序日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13985310/

相关文章:

php - 无法在php中访问访问者的ip地址

php - mysql 出现死锁和锁定超时问题

php - 从分隔字符串中删除尾随分隔字符

php - 创建您自己的 Paypal 请求

php - 使用 jQuery 从 PHP 获取变量值

mysql 查询返回空结果集

php - MySQL - PDO - 如果 POSTS 为 NULL,则允许

java - 从java代码导入mysql数据库

mysql -\!某些命令在远程 mysql 连接中无法正常工作

php - 第一次点击没有更新