Group related records with the highest value in MYSQL

1

Good morning friends, I have the following query:

SELECT
  i.cod_modular, a.idarchivo, m.descripcion, m.cantidad as cantidades,
  d.matriculados, (m.cantidad - d.matriculados) as deficit
FROM archivo a 
JOIN iiee i on i.cod_modular = a.iiee_cod_modular 
JOIN mobiliario m on m.archivo_idarchivo = a.idarchivo 
JOIN detalle d ON d.archivo_idarchivo = a.idarchivo 
WHERE m.descripcion like "%silla%" ORDER by a.idarchivo ASC

Which gives me the following result:

How can I add the amounts of the chairs only of the idarchivo with the highest value of cod_modular ?

I hope your help, greetings :)

    
asked by krcode 26.04.2018 в 23:57
source

2 answers

0

To obtain the sum the function sum () is used, grouping by cod_modular, idarchivo and ordered from highest to lowest, this way we will have the greater idarchivo up in the query.

Then the query is enclosed in another query where we group again but only by cod_modular, in this way it will only give us one record per cod_modular and thanks to the fact that the largest idarfiles are first the value that is maintained when grouped.

The previous description is the following query:

SELECT
t.*  from (SELECT
i.cod_modular, a.idarchivo, m.descripcion, sum(m.cantidad) as cantidades,
d.matriculados, (m.cantidad - d.matriculados) as deficit
FROM archivo a 
JOIN iiee i on i.cod_modular = a.iiee_cod_modular 
JOIN mobiliario m on m.archivo_idarchivo = a.idarchivo 
JOIN detalle d ON d.archivo_idarchivo = a.idarchivo 
WHERE m.descripcion like "%silla%" 
GROUP BY i.cod_modular, a.idarchivo ORDER by a.idarchivo DESC) t group by t.cod_modular
    
answered by 27.04.2018 в 00:32
0

This should work by applying SUM and using GROUP BY HAVING () to filter the result to only the cod_modular with the largest file

SELECT * FROM
(SELECT
  i.cod_modular, a.idarchivo, m.descripcion, SUM(m.cantidad) as cantidades,
  d.matriculados, SUM(m.cantidad - d.matriculados) as deficit
FROM archivo a 
JOIN iiee i on i.cod_modular = a.iiee_cod_modular 
JOIN mobiliario m on m.archivo_idarchivo = a.idarchivo 
JOIN detalle d ON d.archivo_idarchivo = a.idarchivo 
WHERE m.descripcion like "%silla%" GROUP BY i.cod_modular,a.idarchivo) as q 
GROUP BY q.cod_modular HAVING(q.idarchivo = MAX(q.idarchivo)) ORDER by q.idarchivo ASC
    
answered by 27.04.2018 в 15:51