group by analysis of two or more columns

First a brief description of group by:

   It is only meaningful to use group by together with aggregate functions, such as count sum avg, etc., using two elements of group by:
   (1) The fields that appear after select are either in aggregate functions or in group by.
   (2) To filter the results, you can use where and then group by or group by and then having

Let's take a look at the analysis of multiple conditions of group by:

Enter the following statement in the SQL
queryer create table test
(
a varchar(20),
b varchar(20),
c varchar(20)
)

insert into test values(1,'a','甲')
insert into test values(1,'a','甲')
insert into test values(1,'a','甲')
insert into test values(1,'a','甲')
insert into test values(1,'a','乙')
insert into test values(1,'b','乙')
insert into test values(1,'b','乙')
insert into test values(1,'b','乙')

first query

select * from test; The result is as follows:

 

The results are divided according to column b: 5 a and 3 b.


According to column c, there are 4 A and 4 B.


For the second time, the code is grouped according to column b as follows:
select count(a), b from test group by b

For the third time, the code is grouped according to column c as follows:
select count(a), c from test group by c


For the fourth time
, select count(a),b,c from test group by b,c to group according to the two conditions of bc

第五次 按照 c b 顺序分组
select count(a),b,c from test group by c,b

可以看出 group by 两个条件的工作过程:

先对第一个条件b列的值 进行分组,分为 第一组:1-5, 第二组6-8,然后又对已经存在的两个分组用条件二 c列的值进行分组,发现第一组又可以分为两组 1-4,5


来源:http://hi.baidu.com/w_xiaofeng20xx/item/05a2bf154020b97a1009b5e0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326392219&siteId=291194637