举例说明:
table1
a b c
1 aaa xxx
2 bbb yyy
2.5 bbb yyy
3 ccc zzz
执行select sum(a), b from table1 group by b
结果
a b
1 aaa
4.5 bbb
3 ccc
group by的作用就是返回用group by子句里的字段分组,通过聚合函数(sum,max,min等)聚合其他字段的分组聚合结果集;
注意:所有select 子句中的内容必须是group by子句包含的内容或聚合函数聚合的内容,例如:select sum(a), b ,c from table1 group by b是非法的(c不在聚合函数也不在group by子句),select sum(a), b ,c from table1 group by b ,c是合法的,更多更详细的见帮助关于聚合函数的部分
--建立測試環境
Create Table Tb1
(username Varchar(100),
UserCount Int)
--插入數據
Insert Tb1
Select 'A',1
Union All Select 'A',2
Union All Select 'B',5
Union All Select 'B',3
Union All Select 'C',6
--測試
Select username,SUM(UserCount) As TotalCount from Tb1 Group By username Order By username
--刪除測試環境
Drop Table tb1
--結果
/*
username TotalCount
A 3
B 8
C 6
*/