2015-08-20 70 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