Group by variable start and end date variable states

0

I'm working on a graphic of the Timeline type with the google charts API but I depend on a script that creates a new table ("new_tbl") but I do not want to depend on the creation of this one since I have to do it manually every time I want update chart data:

This is the script and later query:

CREATE TABLE new_tbl
SELECT A.id, A.codigo_maquina, A.estado, A.fecha_hora,
  @csum := @csum + 
      IF(A.codigo_maquina = A.prevMachine
         , IF(A.estado = A.prevStatus, 0, A.id
             )
         , A.id
        ) rwGroup
FROM(
      SELECT mch.id, mch.codigo_maquina, mch.estado, mch.fecha_hora
        , @prevStatus prevStatus
        , @prevStatus := mch.estado varPrevStatus
        , @prevObsTime prevObsTime
        , @prevObsTime := mch.fecha_hora varPrevObsTime
        , @prevMachine  prevMachine
        , @prevMachine := mch.codigo_maquina varPrevMachine
      FROM (SELECT @prevStatus := NULL, @prevObsTime := NULL, @prevMachine := NULL) AS dummy 
      CROSS JOIN maquina mch
      ORDER BY mch.codigo_maquina
        , mch.fecha_hora
        , mch.estado ) AS A
CROSS JOIN (SELECT @csum := 0) AS dummy 
GROUP BY  A.id, A.codigo_maquina, A.estado, A.fecha_hora;


SELECT id, codigo_maquina, estado, MIN(fecha_hora), MAX(fecha_hora)
FROM new_tbl
GROUP BY codigo_maquina, estado, rwGroup
ORDER BY codigo_maquina, rwGroup;

This returns the following JSON object:

{
"cols": [{
    "label": "Codigo Maquina",
    "type": "string",
    "id": "Role"
}, {
    "label": "Estado",
    "type": "string",
    "id": "Name"
}, {
    "label": "Hora_Inicio",
    "type": "datetime",
    "id": "Start"
}, {
    "label": "Hora_Fin",
    "type": "datetime",
    "id": "End"
}],
"rows": [{
    "c": [{
        "v": "Maquina 1"
    }, {
        "v": "Fuera de Linea"
    }, {
        "v": "Date(2018, 05, 03, 08, 34, 47)"
    }, {
        "v": "Date(2018, 05, 03, 19, 24, 01)"
    }]
},

The graphic looks good, but I depend on executing the query manually ..

Can I format a new json object in the same way but with php code? or is it better to create a stored procedure in mysql?

Beforehand, thank you very much for your help

    
asked by diegoigr7 04.05.2018 в 02:18
source

1 answer

0

you can use with to generate the first query as a table, then you make the secondary select based on that table, look at: WITH clause , give as an example:

WITH
 cte1 AS (SELECT a, b FROM table1),
 cte2 AS (SELECT c, d FROM table2)
SELECT b, d FROM cte1 JOIN cte2
 WHERE cte1.a = cte2.c;

The other thing would be that you consider implementing business intelligence in your project, having specific tables for that type of reports.

Greetings.

    
answered by 04.05.2018 в 14:58