MySQL - SUM(GROUP BY)?

时间:2011-03-18 00:11:45

标签: mysql sql aggregate-functions

我遇到了一个问题,我需要在select语句中获取一组值的总和。基本上,我需要:

  SELECT col1, col2, SUM(col2) AS col3 
    FROM myTable 
GROUP BY col1

其中col1将结束到大约3组,col2包含大约40个值...所以我不需要col3是相同的值[col2的总和],而是每组col1的col2的总和< / p>

*编辑 * 好的 - 这是实际的查询:


select a.id,a.alloyname,a.label,a.symbol, g.grade, 
    if(a.id = 1,(
        ((( select avg(cost/2204.6) as averageCost 
            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;


我需要按年级分组的'thisValue'总数...试图让我的头围绕它..

2 个答案:

答案 0 :(得分:3)

您可以使用子查询

SELECT col1, col2, (
    select SUM(col2)
    from mytable A
    where A.col1 = myTable.col1) as col3
FROM myTable

答案 1 :(得分:0)

ANSI-92格式:

   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

当没有支持col1引用时,LEFT JOIN将返回NULL - 在此示例中,COALESCE会将这些情况转换为零

ANSI-89格式

SELECT a.col1, 
       a.col2, 
       (SELECT SUM(b.col2)
                   FROM YOUR_TABLE b
                  WHERE b.col1 = a.col1) AS col3
  FROM YOUR_TABLE a

当子查询中没有支持col1引用时,这将返回NULL。