简体   繁体   中英

Pivot table in MySQL with DateTime and dynamic columns

is there a way to achieve this in MySQL?

I have this sample table, the primary key is just a correlative number:

  LotNumber   DateTime              Location
   ABC       07/31/2018 8AM         Start  
   ABC       07/31/2018 10AM        A
   ABC       07/31/2018 2PM         B
   ABC       07/31/2018 5PM         C
   ABC       07/31/2018 9PM         Finished

The customer has a variable production process, where items start and end at different locations. I want to know, when it starts, when it finishes, and how long it stays a different buildings.

The result should look like this:

   LotNumber   Started           Finished         TimeInStart    A    B     C    
   ABC         07/31/2018 8AM    07/31/2018 9PM   2H             4H   3H    3H

Number of columns may change, so it has to be dynamic.

Consider the following:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,dt DATETIME NOT NULL
,location CHAR(1) NOT NULL
);

INSERT INTO my_table VALUES
(1,'2018-07-31 08:00:00','A'),
(2,'2018-07-31 10:00:00','X'),
(3,'2018-07-31 14:00:00','Y'),
(4,'2018-07-31 17:00:00','Z'),
(5,'2018-07-31 21:00:00','B');

SELECT x.*
     , TIMEDIFF(MIN(y.dt),x.dt) diff 
  FROM my_table x 
  LEFT 
  JOIN my_table y ON y.dt > x.dt 
 GROUP 
    BY x.id;
+----+---------------------+----------+----------+
| id | dt                  | location | diff     |
+----+---------------------+----------+----------+
|  1 | 2018-07-31 08:00:00 | A        | 02:00:00 |
|  2 | 2018-07-31 10:00:00 | X        | 04:00:00 |
|  3 | 2018-07-31 14:00:00 | Y        | 03:00:00 |
|  4 | 2018-07-31 17:00:00 | Z        | 04:00:00 |
|  5 | 2018-07-31 21:00:00 | B        | NULL     |
+----+---------------------+----------+----------+

Any remaining aspects to the problem are best resolved in application code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM