sum()by group sql

时间:2015-08-20 08:51:56

标签: php sql

我的数据排成一行,下面有相同的valueid示例:

table_name:test

id | amount
 1 |   100
 1 |   100
 1 |   100 
 2 |   150
 2 |   150
 2 |   150
 3 |   200
 3 |   200
 3 |   200
 4 |   250
 4 |   250
 4 |   250

我想在每个id中仅使用sql对一行进行求和,而不是对所有行进行求和。

"select *, sum(amount) as total from test group by id";

我的问题是sum()只有一个row id可能?

所需的输出? 编辑

id | amount
 1 |   100
 2 |   150
 3 |   200
 4 |   250

total : 700

5 个答案:

答案 0 :(得分:1)

看起来你需要这个

select *,sum(amount) from (select distinct * from test) as t group by id

答案 1 :(得分:1)

尝试:

select id, sum(amount)/count(*) as total 
from test 
group by id

结果:

| id | total |
|----|-------|
|  1 |   100 |
|  2 |   150 |
|  3 |   200 |
|  4 |   250 |

答案 2 :(得分:1)

使用子查询 -

尝试此操作
select sum(amount) from (select distinct id,amount from company7) as tempTable

答案 3 :(得分:1)

  

我的问题是sum()每个id只能有一行吗?

我将此解释为您想要的一个值,每个组都有一行。一种方法是两级聚合:

select sum(amount)
from (select id, max(amount) as amount
      from test
      group by id
     ) t;

答案 4 :(得分:1)

试试这个

create table #test
(id int, amount int)

insert into #test values (1,100),(1,100),(1,100),(2,150),(2,150),(3,200),(3,250)

;with cte
as
(
select sum(distinct amount) as damount,id
from #test
group by id
)

select sum(damount) as total from cte

对于除SQL Server之外的其他DBMS

select sum(damount) as total from (select sum(distinct amount) as damount,id
from test
group by id) as it