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
)
第二种解决方案使用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
)
试试这个
SELECT SUM( value ) AS valuesum, codebook
FROM stock
GROUP BY codebook
ORDER BY valuesum DESC
LIMIT 1
您可以通过单个查询简单地获取它 -
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
演示:-http://sqlfiddle.com/#!9/ c2534 /15
试试这个
SELECT TOP 1 * FROM
(
SELECT SUM([value]) AS valuesum, codebook
FROM stock
GROUP BY codebook
)
ORDER BY valuesum DESC
假设(根据评论和错误消息)您使用 MySQL:
SELECT SUM( value ) AS valuesum, codebook
FROM stock
GROUP BY codebook
ORDER BY valuesum DESC
LIMIT 1 ;