MySQL - SUM(GROUP BY)?
I'm having an issue where I need to get the sum of a group of values in a select statement,. Basically, I need to:
SELECT col1, col2, SUM(col2) AS col3
FROM myTable
GROUP BY col1
where col1 will wind up into about 3 groups and col2 contains around 40 values... so I don't need col3 to be the same value [the sum of col2] but the sum for col2 for each group of col1
* EDIT * ok - here is the actual query:
select a.id,a.alloyname,a.label,a.symbol, g.grade,
if(a.id = 1,(
((( select avg(cost/2204.6) as averag开发者_如何学PythoneCost
from nas_cost where cost != '0'
and `date` >= '#variables.firstOfMonth#'
and `date` <= '#variables.lastOfMonth#') - t.value) * (astm.astm/100) * 1.2)),
if(a.id = 2,(
((ep.estPrice - t.value) * (astm.astm/100) * 1.2)),
if(a.id = 3 or a.id = 4 or a.id = 6 or a.id = 7,(
((ep.estPrice - t.value) * (astm.astm/100) * 0.012)),
if(a.id = 5,(
((ep.estPrice - t.value)/2240 * (astm.astm/100))),
if(a.id = 8,(
if(((ep.estPrice - t.value)* (astm.astm/100)) >= 0,((ep.estPrice - t.value)* (astm.astm/100)), 0)),
0)))))
as thisValue
from nas_alloys a
left join nas_triggers t on t.alloyid = a.id
left join nas_astm astm on astm.alloyid = a.id
left join nas_estimatedprice ep on ep.alloyid = a.id
left join nas_grades g on g.id = astm.gradeid
order by g.grade;
I need the total of 'thisValue' grouped by grade... trying to get my head around it..
You can use a subquery for this
SELECT col1, col2, (
select SUM(col2)
from mytable A
where A.col1 = myTable.col1) as col3
FROM myTable
ANSI-92 Format:
SELECT a.col1,
a.col2,
COALESCE(b.col3, 0) AS col3
FROM YOUR_TABLE a
LEFT JOIN (SELECT t.col1,
SUM(t.col2) AS col3
FROM YOUR_TABLE t
GROUP BY t.col1) b ON b.col1 = a.col1
The LEFT JOIN will return NULL when there's no supporting col1 reference -- COALESCE will convert those situations into zero in this example
ANSI-89 Format
SELECT a.col1,
a.col2,
(SELECT SUM(b.col2)
FROM YOUR_TABLE b
WHERE b.col1 = a.col1) AS col3
FROM YOUR_TABLE a
This will return NULL when there's no supporting col1 reference in the subquery.
精彩评论