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哪一个 ,且要用聚合函数