關於group by 兩個或以上條件的分析

首先group by 的簡單說明:函數

group by 通常和聚合函數一塊兒使用纔有意義,好比 count sum avg等,使用group by的兩個要素: (1) 出如今select後面的字段 要麼是是聚合函數中的,要麼就是group by 中的. (2) 要篩選結果 能夠先使用where 再用group by 或者先用group by 再用having圖片

下面看下 group by多個條件的分析: 在SQL查詢器輸入如下語句 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','乙')it

  • 這裏是列表文本第一次查詢 select * from test; 結果以下圖:

輸入圖片說明

結果中 按照b列來分:則是 5個a 3個b.table

按照c列來分:則是 4個甲 4個乙.test

  • 這裏是列表文本第二次 按照 b列來分組 代碼以下 select count(a),b from test group by b

輸入圖片說明

  • 這裏是列表文本第三次 按照 c列來分組 代碼以下 select count(a),c from test group by c

輸入圖片說明

  • 這裏是列表文本第四次 按照 b c兩個條件來分組 select count(a),b,c from test group by b,c

輸入圖片說明

  • 這裏是列表文本第五次 按照 c b 順序分組 select count(a),b,c from test group by c,b

輸入圖片說明 能夠看出 group by 兩個條件的工做過程: 先對第一個條件b列的值 進行分組,分爲 第一組:1-5, 第二組6-8,而後又對已經存在的兩個分組用條件二 c列的值進行分組,發現第一組又能夠分爲兩組 1-4,5select

相關文章
相關標籤/搜索