20190423更新:自己建立了函數查閱了經常犯的錯誤,要attention(在最後)
---------
count/sum/min/avg 等等聚合函數值作用非null,那些null自動忽略了
2.sum隻垂直加總(除非。。)
3.min、max既可以作用非數值也可以作用數值
4.count(distinct)常常聯用
5.case語句在group by裡十分好用!
6. case技巧2sum+case行結構變成列結構
7.case如果省略else,預設其他情況都是null了,是以記得要加上
經典例題1:求求多列的最大數
思路1:
思路二
經典例題2:
思路解析:groupby男女,之後我再select!!!!注意前後順序
CREATE TABLE Poptbl2
(
pref_name VARCHAR(50) NOT NULL,
sex INT NOT NULL,
population INT NOT NULL
);
INSERT INTO Poptbl2 VALUES('德島',1,60);
INSERT INTO Poptbl2 VALUES('德島',2,40);
INSERT INTO Poptbl2 VALUES('香川',1,100);
INSERT INTO Poptbl2 VALUES('香川',2,100);
INSERT INTO Poptbl2 VALUES('愛媛',1,100);
INSERT INTO Poptbl2 VALUES('愛媛',2,50);
INSERT INTO Poptbl2 VALUES('高知',1,100);
INSERT INTO Poptbl2 VALUES('高知',2,100);
INSERT INTO Poptbl2 VALUES('福岡',1,100);
INSERT INTO Poptbl2 VALUES('福岡',2,200);
INSERT INTO Poptbl2 VALUES('佐賀',1,20);
INSERT INTO Poptbl2 VALUES('佐賀',2,80);
INSERT INTO Poptbl2 VALUES('長崎',1,125);
INSERT INTO Poptbl2 VALUES('長崎',2,125);
INSERT INTO Poptbl2 VALUES('東京',1,250);
INSERT INTO Poptbl2 VALUES('東京',2,150);
行列結構互換
-- 第一題
SELECT pref_name,
CASE WHEN sex = 1 THEN population ELSE NULL END AS '男',
CASE WHEN sex = 2 THEN population ELSE NULL END AS '女'
FROM Poptbl2;
不對
沒有groupby這裡德島出現多次,因為就是選的每一行啊,是以groupby之後隻出現一次,避免上面的問題
SELECT pref_name,
SUM(CASE WHEN sex = 1 THEN population ELSE NULL END) AS '男',
SUM(CASE WHEN sex = 2 THEN population ELSE NULL END) AS '女'
FROM Poptbl2
GROUP BY pref_name;
但是聚合函數要加上,不加上的後果如下
SELECT pref_name,
CASE WHEN sex = 1 THEN population ELSE NULL END AS '男',
CASE WHEN sex = 2 THEN population ELSE NULL END AS '女'
FROM Poptbl2
GROUP BY pref_name;
第二題
SELECT sex AS '性别',
SUM(population) AS '全國',
SUM(CASE WHEN pref_name = '德島' THEN population ELSE NULL END) AS '德島',
SUM(CASE WHEN pref_name = '香川' THEN population ELSE NULL END) AS '香川',
SUM(CASE WHEN pref_name = '愛媛' THEN population ELSE NULL END) AS '愛媛',
SUM(CASE WHEN pref_name = '高知' THEN population ELSE NULL END) AS '高知',
FROM Poptbl2
GROUP BY sex;
總結:看看先groupby哪一個 ,且要用聚合函數