group by 兩個字段

 

group by 的簡單說明:  group by 通常和聚合函數一塊兒使用纔有意義,好比 count sum avg等函數

使用group by的兩個要素:
   (1) 出如今select後面的字段 要麼是是聚合函數中的,要麼就是group by 中的.
   (2) 要篩選結果 能夠先使用where 再用group by 或者先用group by 再用having測試

 

 

下面看下 group by多個條件的分析:3d

---------- 測試數據初始化    begin --------------------blog

在SQL查詢器輸入如下語句table

create table test1
(
a varchar2(20),
b varchar2(20),
c varchar2(20)
);
insert into test1 values(1,'a','甲');
insert into test1 values(1,'a','甲');
insert into test1 values(1,'a','甲');
insert into test1 values(1,'a','甲');
insert into test1 values(1,'a','乙');
insert into test1 values(1,'b','乙');
insert into test1 values(1,'b','乙');
insert into test1 values(1,'b','乙');test

---------- 測試數據初始化    end--------------------select

第一次查詢im

select * from test1; 結果以下圖:d3

結果中       按照b列來分:則是 5個a 3個b.    按照c列來分:則是 4個甲 4個乙.數據

 

第二次查詢 按照 b列來分組 代碼以下

select count(a),b from test1 group by b;

 

 

第三次 按照 c列來分組 代碼以下
select count(a),c from test1 group by c;

 


第四次 按照 b c兩個條件來分組

select count(a),b,c from test1 group by b,c;

能夠看出 group by 兩個條件的工做過程:

先對第一個條件b列的值 進行分組,分爲 第一組:1-5, 第二組6-8,

而後又對已經存在的兩個分組用條件二 c列的值進行分組,發現第一組又能夠分爲兩組 1-4,5

 

第五次 按照 c b 順序分組

select count(a),b,c from test1 group by c,b;

相關文章
相關標籤/搜索