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

全國咨詢/投訴熱線:400-618-4000

MySQL數據庫基本操作:聚合查詢和分組查詢

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

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

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

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

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

NULL值的處理

count函數對null值的處理,如果count函數的參數為星號(*),則統(tǒng)計所有記錄的個數。而如果參數為某字段,不統(tǒng)計含null值的記錄個數。

sum和avg函數對null值的處理,這兩個函數忽略null值的存在,就好象該條記錄不存在一樣。

max和min函數對null值的處理,max和min兩個函數同樣忽略null值的存在。

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

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

-- 插入數據
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);
 
-- 測試
select count(*), count(1), count(c2) from test_null;
select sum(c2),max(c2),min(c2),avg(c2) from test_null;

0 分享到:
和我們在線交談!