1
code   || Name|| day||ActivityDate||TimeIn    || TimeOut  ||
 001   || Ade || 02 || 2013-08-02 || 10:06:09 || 18:21:03 ||
 001   || Ade || 03 ||2013-08-03  || 11:00:34 || 18:06:56 ||
 001   || Ade || 05 || 2013-08-05 || 09:56:29 || 17:59:56 ||
 002   || Ali || 01 || 2013-08-01 || 09:56:29 || 17:59:56 ||

这是我在phpmyadmin中的表..我想查询,它会像另一个表一样..

  code|| Name||  1.8TimeIn  ||1.8TimeOut|| 2.8TimeIn|| 2.8TimeOut || And so on>>>
  001 || Ade ||  NULL       || NULL     || 10:06:09 ||  18:21:03  ||  
  002 || Ali ||  09:56:29   || 17:59:56 || NULL     ||  NULL      ||

如果我不想查询如何使用数组,如果我使用查询,将需要很长时间才能阅读..

我的示例查询:

SELECT Name, EmployeeID,
   (SELECT TimeIn  FROM augustatt 
      WHERE EmployeeID=M.EmployeeID AND ActivityDate='2013-08-01') AS '1/8In',
   (SELECT TimeOut  FROM augustatt 
      WHERE EmployeeID=M.EmployeeID AND ActivityDate='2013-08-01') AS '1/8Out' 
FROM augustatt M 
GROUP BY Name,EmployeeID 
ORDER BY Name
4

1 回答 1

2

您的基本静态查询应如下所示

SELECT code, name,
       MAX(CASE WHEN ActivityDate = '2013-08-01' THEN timein  END) timein_0108,
       MAX(CASE WHEN ActivityDate = '2013-08-01' THEN timeout END) timeout_0108,
       MAX(CASE WHEN ActivityDate = '2013-08-02' THEN timein  END) timein_0208,
       MAX(CASE WHEN ActivityDate = '2013-08-02' THEN timeout END) timeout_0208,
       ...
 FROM augustatt
 GROUP BY code, name

样本输出:

+------+------+-------------+--------------+------ --------+--------------+
| 代码 | 姓名 | timein_0108 | 超时_0108 | timein_0208 | 超时_0208 |
+------+------+-------------+--------------+------ --------+--------------+
| 1 | 阿德 | 空 | 空 | 10:06:09 | 18:21:03 |
| 2 | 阿里 | 09:56:29 | 17:59:56 | 空 | 空 |
+------+------+-------------+--------------+------ --------+--------------+

这是SQLFiddle演示


现在您可以通过这种方式进行动态旋转

DELIMITER $$
CREATE PROCEDURE sp_report()
BEGIN
  SET @sql = NULL;

  SELECT GROUP_CONCAT(DISTINCT 
                      CONCAT('MAX(CASE WHEN ActivityDate = ''', ActivityDate,
                             ''' THEN timein  END) timein_', 
                             DATE_FORMAT(ActivityDate, '%d%m'), 
                             ',MAX(CASE WHEN ActivityDate = ''', ActivityDate,
                             ''' THEN timeout  END) timeout_', 
                             DATE_FORMAT(ActivityDate, '%d%m')))
    INTO @sql
    FROM augustatt;

  SET @sql = CONCAT('SELECT code, name,', @sql,
                    '  FROM augustatt
                      GROUP BY code, name');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

并使用它

CALL sp_report();

这是SQLFiddle演示

于 2013-09-09T08:43:29.080 回答