将列转换为行..复杂的东西对我来说..只是一个初学者

时间:2013-12-26 00:05:37

标签: php mysql select pivot

这是我的表格输入/输出

emp_id    td_id    status     timestamp          remarks
  35        1        in   2013-12-19 10:15:09     late
  35        2        out  2013-12-19 12:00:23     example
  36        3        in   2013-12-19 10:15:09    
  36        4        out  2013-12-19 12:00:23     example

如何制作像这样的选择查询

emp_id   status     timestamp        status     timestamp          remarks
  35       in   2013-12-19 10:15:09   out  2013-12-19 12:00:23  late, example
  36       in   2013-12-19 10:15:09   out  2013-12-19 12:00:23      example

sqlfiddle&lt; -----现有代码(我有3对输入/输出。):)我如何在这3对进出中添加备注?... < / p>

1 个答案:

答案 0 :(得分:0)

sqlFiddle

SELECT rec1.emp_id,rec1.status as status1,rec1.timestamp as timestamp1,
                   rec2.status as status2,rec2.timestamp as timestamp2,
       CASE WHEN IFNULL(rec1.remarks,'') = '' THEN IFNULL(rec2.remarks,'')
            WHEN IFNULL(rec2.remarks,'') = '' THEN IFNULL(rec1.remarks,'')
            ELSE CONCAT(IFNULL(rec1.remarks,''),',',IFNULL(rec2.remarks,''))
       END as remarks
FROM
    (SELECT emp_id,timestamp as timestampin,
           (SELECT MIN(timestamp)
            FROM overallrec t2
            WHERE t2.timestamp > t1.timestamp
              AND status = 'out'
            )as timestampout
    FROM overallrec t1
    WHERE status = 'in')InOutTime
LEFT JOIN overallrec rec1 ON (InOutTime.timestampin = rec1.timestamp
                              AND rec1.status = 'in'
                              AND rec1.emp_id = InOutTime.emp_id)
LEFT JOIN overallrec rec2 ON (InOutTime.timestampout = rec2.timestamp
                              AND rec2.status = 'out'
                              AND rec2.emp_id = InOutTime.emp_id)

要有3对,我使用现有的3对代码,并通过emp_id,formattedDate将它与T5,GROUP_CONCAT组LEFT JOIN。检查此sqlFiddle