SQL中GROUP BY的学习理解

2018-07-03  本文已影响13人  Coder_Cat
CREATE TABLE aatest(
id NUMBER(6,0),
username VARCHAR2(255),
num NUMBER(30,0)
) 
INSERT INTO aatest VALUES (1,'aa',2); 
INSERT INTO aatest VALUES (2,'aa',3); 
INSERT INTO aatest VALUES (3,'bb',4); 
INSERT INTO aatest VALUES (4,'cc',3); 
INSERT INTO aatest VALUES (5,'dd',4); 
INSERT INTO aatest VALUES (6,'dd',5);
INSERT INTO aatest VALUES (7,'ee',6); 
INSERT INTO aatest VALUES (8,'ee',7);
INSERT INTO aatest VALUES (9,'ee',6); 
创建表格数据.png
SELECT username
FROM aatest
GROUP BY username;
单个关键字GROUP BY使用.png
SELECT username, sum(num) AS sumnum 
FROM aatest 
GROUP BY username;
结合聚合函数.png
即同一个username下的num求和。
SELECT username,avg(id)
FROM aatest
GROUP BY username,num;
多个字段` GROUP BY` .png

因为只有两条记录是一样的,所以这两条合成一条计算,整体少了一条数据。

上一篇下一篇

猜你喜欢

热点阅读