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
                     )

SQL Fiddle演示
使用having条件的第二种溶液:
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演示

08-05 05:14