SQL --------------- GROUP BY 函數

Aggregate 函數經常須要添加 GROUP BY 語句,Aggregate函數也就是常說的聚和函數,也叫集合函數函數

GROUP BY語句一般與集合函數(COUNT,MAX,MIN,SUM,AVG)一塊兒使用,以按一個或多個列對結果集進行分組。spa

語法:code

select 聚合函數(字段),字段  from 表名 group by  字段

建個表,弄點數,爲了方便對照blog

 

 

 分組查詢銀行統計名字相同的有幾個排序

select COUNT(字段) as 個數,字段a from 表名 group by 字段a

其中count 中的字段能夠隨意填,通常爲idrem

 

 

有可能的報錯:get

只又分組查詢的那個字段能夠不用聚合函數it

 

 

 能夠稍加修改:class

分組查詢銀行,並統計工資總數test

 

 

 與top 一塊進行查詢

語法:

select top 查詢前幾行 COUNT(字段) as 個數,字段a from 表名 group by 字段a

 

 

 與排序 order by  一塊

語法:     字段要一致

select top 查詢前幾行 COUNT(字段) as 個數,字段a from 表名 group by 字段a order by 字段a desc

 

 

 若是不一致

 

 

 與where 字句一塊使用

語法:       count()  裏面沒有什麼限制,放啥都行

select top 查詢前幾行 COUNT(0) as 個數,字段a from 表名 where 條件 group by 字段a order by 字段a desc

 

 多表查詢

語法:

SELECT 表1.name,COUNT(表2.aid) AS nums FROM 表2
INNER JOIN 表1
ON 表2.site_id=表1.id
GROUP BY 表1.name;

 

 

select * from obgetest 
--  分組查詢 銀行,,其中名字是 obge 的有兩個
select COUNT(Gids) as 個數,Bank from obgetest group by Bank

---  能夠看出,多個字段時,只有須要分組查詢的那個字段能夠不用使用聚合函數
select COUNT(Gids)as 個數,Bank,Gongzi from obgetest group by Bank

-- 能夠修改成分組查詢銀行,並統計工資總總數
select COUNT(Gids)as 個數,Bank,sum(Gongzi)as 總數 from obgetest group by Bank

--  與top 一塊查詢,count 裏面放入bank 字段和 gids 字段的做用一致
select top 5 COUNT(Bank) as 個數,Bank from obgetest group by Bank

--  與order by 一塊,分組查詢工資相同個數, 並按照倒序排列,查前5 行
-----  必定要注意 排序的字段和分組字段要一致
select top 5 COUNT(rem) as 個數,Gongzi from obgetest group by Gongzi order by Gongzi desc
---  有錯誤
select top 5 COUNT(rem) as 個數,Gongzi from obgetest group by Gongzi order by Gids desc

----   與where字句   注意語法位置
select  COUNT(0) as 個數,Gongzi from obgetest where Gongzi > 1000 group by Gongzi order by Gongzi desc
相關文章
相關標籤/搜索