2015-08-20 72 views
0

我有下同valueid例如在一排数据:总和()由组SQL

表名:测试

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 
+2

什么是所需的输出? – DarkKnight

+0

@DarkKnight更新我上面的问题。 – jhunlio

+0

你想要总输出还是上表作为输出?或两者? – DarkKnight

回答

1

我的问题是,可能要总结()只有一排每个ID?

我把它解释为你想要的一个值,每个组都有一行。一种方法是聚集的两个层次:

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

看起来你需要这个

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

它与我上面的查询返回相同的结果。 – jhunlio

+0

使用wildchar结合组是不好的做法 –

1

尝试:

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

结果:

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

尝试这种使用subquery-

select sum(amount) from (select distinct id,amount from company7) as tempTable 
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 

对于其他DBMS于SQL Server

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