본문 바로가기
MySql

MySQL Select Max Data from Subquery SQL, but it Show All Results from Subquery

by 베이스 공부 2021. 1. 27.
반응형
SELECT MAX( t.valuesum ) AS total, t.codebook
FROM (
    SELECT SUM( value ) AS valuesum, codebook
    FROM stock
    GROUP BY codebook
) t
GROUP BY t.codebook

하위 쿼리에서 출력은 다음과 같습니다.

b001 35,
b002 20,
b0003 11

보고 싶은 건 : b001 35. 제발 도와주세요.

 

해결 방법

 

where 조건을 사용하는 첫 번째 솔루션 :

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
                     ) 


있음 조건을 사용하는 두 번째 솔루션 :

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
                     )


 

참조 페이지 https://stackoverflow.com/questions/12562389

 

 

반응형

댓글