如何查询垂直和快速读取

时间:2013-09-09 08:29:19

标签: mysql

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

1 个答案:

答案 0 :(得分: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

示例输出:

+------+------+-------------+--------------+-------------+--------------+
| code | name | timein_0108 | timeout_0108 | timein_0208 | timeout_0208 |
+------+------+-------------+--------------+-------------+--------------+
|    1 | Ade  | NULL        | NULL         | 10:06:09    | 18:21:03     |
|    2 | Ali  | 09:56:29    | 17:59:56     | NULL        | NULL         |
+------+------+-------------+--------------+-------------+--------------+

这是 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 演示