2010-10-28 35 views
7

Oye, tengo un problema con una consulta SQL. Vamos a tomar este ejemplo, los datosSQL: utilizando GROUP BY y MAX en varias columnas

itemID catID attrib1 attrib2 
    1  1  10  5 
    2  1  10  7 
    3  1  5  10 
    4  2  18  15 

quiero devolver el mejor elemento para cada categoría (con attrib1 tener prioridad sobre attrib2)

Obviamente, "SELECT catID, MAX (attrib1), MAX (attrib2) DE test_table GROUP BY catID "no funciona, ya que devolverá 10 & 10 para el 1er gato.

Entonces, ¿hay alguna manera de decirle a MySQL que seleccione el valor máximo de la fila attrib2 pero solo considere aquellos en los que attrib1 también es el valor máximo? es decir, devolver los datos siguientes

catID attrib1 attrib2 
    1  10  7 
    2  18  15 

Respuesta

6

, usted puede obtener los mejores valores attrib1, y luego unirse a los valores attrib2 y obtener el mejor de los que para cada valor attrib1:

select t2.catID, t2.attrib1, max(t2.attrib2) 
from 
(
    select catID, max(attrib1) as attrib1 
    from test_table 
    group by catID 
) t1 
inner join test_table t2 on t2.catID = t1.catID and t2.attrib1 = t1.attrib1 
group by t2.catID, t2.attrib1 
+0

Gracias por todas las respuestas rápidas chicos. También es bueno ver diferentes formas de hacerlo. – Charles

+0

¿Funciona? los 3 valores que regresan deben ser los de filas diferentes. – Ryo

1
SELECT tt.catId, tt.attrib1, MAX(tt.attrib2) 
FROM test_table tt 
GROUP BY tt.catID, tt.attrib1 
WHERE tt.attrib1 = (SELECT MAX(t2.attrib1) FROM test_table t2 WHERE t2.catID = tt.catID) 
-1
SELECT catID, max1, max2 FROM 
((SELECT Max(attrib1) as max1, catID GROUP BY attrib1) as t1 
INNER JOIN 
(SELECT MAX(attrib2) as max2, catID GROUP BY attrib2) as t2 
ON t1.catID = t2.catID) as t3 
1

Uso:

SELECT x.catid, 
     x.max_attrib1 AS attrib1, 
     (SELECT MAX(attrib2) 
      FROM YOUR_TABLE y 
     WHERE y.catid = x.catid 
      AND y.attrib1 = x.max_attrib1) AS attrib2 
    FROM (SELECT t.catid, 
       MAX(t.attrib1) AS max_attrib1 
      FROM YOUR_TABLE t 
     GROUP BY t.catid) x 
Cuestiones relacionadas