如何使用mysql选择表中不同值的总和

时间:2012-07-06 21:25:32

标签: mysql sql

slno state district company 
1     a       ab     abc
2     a       ab     ac
3     a       ab     abc
4     a       ab     abc
5     a       ab     abc
6     a       ab     ac

输出

state district company sumzz
 a      ab       abc    4
 a      ab       ac     2

我尝试了什么

select state,district,company,sum(company) as sumzz from company

如何根据不同的公司实现显示最后一行?

4 个答案:

答案 0 :(得分:2)

编辑:对于更新的问题,您可以在子查询中检索最大slno。然后,您可以使用in来过滤那些:

select  state
,       district
,       company
,       slno
from    Company
where   slno in
        (
        select  max(slno)
        from    Company
        group by
                state
        ,       district
        ,       company
        )

答案 1 :(得分:2)

这种方法有什么问题:

  SELECT state, district, company, COUNT(*) as countzz
    FROM company
GROUP BY state, district, company

答案 2 :(得分:2)

我认为你试图计算有多少记录而不是总结一些东西。如果这就是你想要的,那么你应该这样做:

SELECT state, district, company, COUNT(*) as sumzz 
FROM company
GROUP BY state, district, company

答案 3 :(得分:0)

从公司='abc'

的公司选择州,区,公司,总和(公司)作为sumzz