Mysql
 sql >> Base de données >  >> RDS >> Mysql

Sélectionnez Max Data from Subquery SQL, mais il affiche tous les résultats de la sous-requête

1ère solution utilisant where condition :

SELECT t1.valuesum, t1.codebook
FROM (
        SELECT SUM( s.value ) AS valuesum, s.codebook
        FROM stock s
        GROUP BY s.codebook
     ) t1
WHERE t1.valuesum in (SELECT MAX( t2.valuesum ) AS total
                     FROM (
                             SELECT SUM( s2.value ) AS valuesum, s2.codebook
                             FROM stock s2
                             GROUP BY s2.codebook
                           )t2
                     ) 

SQL Fiddle Démo

2ème solution utilisant having condition :

SELECT max(t1.valuesum), t1.codebook
FROM (
        SELECT SUM( s.value ) AS valuesum, s.codebook
        FROM stock s
        GROUP BY s.codebook
     ) t1
GROUP BY t1.codebook
HAVING max(t1.valuesum) = (SELECT MAX( t2.valuesum ) AS total
                     FROM (
                             SELECT SUM( s2.value ) AS valuesum, s2.codebook
                             FROM stock s2
                             GROUP BY s2.codebook
                           )t2
                     )

SQL Fiddle Démo