教育行業(yè)A股IPO第一股(股票代碼 003032)

全國(guó)咨詢/投訴熱線:400-618-4000

MySQL數(shù)據(jù)庫(kù)基本操作:聚合查詢和分組查詢

更新時(shí)間:2023年11月10日11時(shí)15分 來源:傳智教育 瀏覽次數(shù):

之前我們做的查詢都是橫向查詢,它們都是根據(jù)條件一行一行的進(jìn)行判斷,而使用聚合函數(shù)查詢是縱向查詢,它是對(duì)一列的值進(jìn)行計(jì)算,然后返回一個(gè)單一的值;另外聚合函數(shù)會(huì)忽略空值。

-- 1 查詢商品的總條數(shù)
select count(*) from product;
-- 2 查詢價(jià)格大于200商品的總條數(shù)
select 
count(*) from product where price > 200;
-- 3 
查詢分類為'c001'的所有商品的總和
select sum(price) from product where category_id = 
'c001';
-- 4 查詢商品的最大價(jià)格
select max(price) from product;
-- 5 
查詢商品的最小價(jià)格
select min(price) from product;
-- 6 
查詢分類為'c002'所有商品的平均價(jià)格
select avg(price) from product where category_id = 
'c002';

聚合查詢操作的示例代碼如下:

-- 1 查詢商品的總條數(shù)
select count(*) from product;
-- 2 查詢價(jià)格大于200商品的總條數(shù)
select count(*) from product where price > 200;
-- 3 查詢分類為'c001'的所有商品的總和
select sum(price) from product where category_id = 'c001';
-- 4 查詢商品的最大價(jià)格
select max(price) from product;
-- 5 查詢商品的最小價(jià)格
select min(price) from product;
-- 6 查詢分類為'c002'所有商品的平均價(jià)格
select avg(price) from product where category_id = 'c002';

NULL值的處理

count函數(shù)對(duì)null值的處理,如果count函數(shù)的參數(shù)為星號(hào)(*),則統(tǒng)計(jì)所有記錄的個(gè)數(shù)。而如果參數(shù)為某字段,不統(tǒng)計(jì)含null值的記錄個(gè)數(shù)。

sum和avg函數(shù)對(duì)null值的處理,這兩個(gè)函數(shù)忽略null值的存在,就好象該條記錄不存在一樣。

max和min函數(shù)對(duì)null值的處理,max和min兩個(gè)函數(shù)同樣忽略null值的存在。

NULL值的處理操作,示例代碼如下:

-- 創(chuàng)建表
create table test_null( 
 c1 varchar(20), 
 c2 int 
);

-- 插入數(shù)據(jù)
insert into test_null values('aaa',3);
insert into test_null values('bbb',3);
insert into test_null values('ccc',null);
insert into test_null values('ddd',6);
 
-- 測(cè)試
select count(*), count(1), count(c2) from test_null;
select sum(c2),max(c2),min(c2),avg(c2) from test_null;

0 分享到:
和我們?cè)诰€交談!