问题
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
In the subquery, the output is :
b001 35,
b002 20,
b0003 11
I want to only see: b001 35. Please help me.
回答1:
1st solution using 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 Demo
2nd solution using 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 Demo
回答2:
Try this
SELECT SUM( value ) AS valuesum, codebook
FROM stock
GROUP BY codebook
ORDER BY valuesum DESC
LIMIT 1
回答3:
You can simple get it by single query -
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
回答4:
Try this
SELECT TOP 1 * FROM
(
SELECT SUM([value]) AS valuesum, codebook
FROM stock
GROUP BY codebook
)
ORDER BY valuesum DESC
回答5:
Assuming (from the comments and the error messages) that you use MySQL:
SELECT SUM( value ) AS valuesum, codebook
FROM stock
GROUP BY codebook
ORDER BY valuesum DESC
LIMIT 1 ;
来源:https://stackoverflow.com/questions/12562389/select-max-data-from-subquery-sql-but-it-show-all-results-from-subquery