从子查询SQL中选择最大数据,但它从子查询显示所有结果

时间:2012-09-24 09:37:59

标签: mysql sql subquery

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.请帮助我。

5 个答案:

答案 0 :(得分:2)

试试这个

SELECT SUM( value ) AS valuesum, codebook 
FROM stock 
GROUP BY codebook
ORDER BY valuesum DESC
LIMIT 1

答案 1 :(得分:2)

使用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演示

答案 2 :(得分:0)

试试这个

SELECT TOP 1 * FROM
(
  SELECT SUM([value]) AS valuesum, codebook
  FROM stock
  GROUP BY codebook
)
ORDER BY valuesum DESC

答案 3 :(得分:0)

假设您(使用注释和错误消息)使用MySQL:

SELECT SUM( value ) AS valuesum, codebook
FROM stock
GROUP BY codebook
ORDER BY valuesum DESC
  LIMIT 1 ;

答案 4 :(得分:0)

您可以通过单个查询简单地获取它 -

    SELECT MAX( t2.valuesum ) AS valuesum, t2.codebook
    FROM (
          SELECT SUM( s2.value ) AS valuesum, s2.codebook
          FROM stock s2
          GROUP BY s2.codebook
         )t2

DEMO: - http://sqlfiddle.com/#!9/c2534/15