1.oracle中decode函数的使用
--创建表
Create Table stu_score(
stu_name varchar2(50),
subject Varchar2(50),
score Number
Insert Into stu_score Values('张三','语文',30);
Insert Into stu_score Values('张三','数学',40);
Insert Into stu_score Values('张三','英语',50);
Insert Into stu_score Values('李四','语文',60);
Insert Into stu_score Values('李四','数学',80);
Insert Into stu_score Values('李四','英语',90);
Insert Into stu_score Values('王五','语文',90);
Insert Into stu_score Values('王五','数学',100);
--普通查询的效果
Select * From stu_score
--使用decode函数后的效果
Select stu_name, sum(decode(subject,'语文',score))语文,
sum(decode(subject,'数学',score))数学,
sum(decode(subject,'英语',score))英语
From stu_score Group By stu_name;
--需要注意说明:当同时含有where子句、group by子句 、having子句及聚集函数时,执行顺序如下:
--执行where子句查找符合条件的数据;
--使用group by子句对数据进行分组;对group by子句形成的组运行聚集函数计算每一组的值;最后用having子句去掉不符合条件的组。
--having子句中的每一个元素也必须出现在select列表中。有些数据库例外,如oracle。
--having子句和where子句都可以用来设定限制条件以使查询结果满足一定的条件限制。
--having子句限制的是组,而不是行。where子句中不能使用聚集函数,而having子句中可以。
--创建表
Create Table stu_score(
stu_name varchar2(50),
subject Varchar2(50),
score Number
);
--测试数据Insert Into stu_score Values('张三','语文',30);
Insert Into stu_score Values('张三','数学',40);
Insert Into stu_score Values('张三','英语',50);
Insert Into stu_score Values('李四','语文',60);
Insert Into stu_score Values('李四','数学',80);
Insert Into stu_score Values('李四','英语',90);
Insert Into stu_score Values('王五','语文',90);
Insert Into stu_score Values('王五','数学',100);
--普通查询的效果
Select * From stu_score
--使用decode函数后的效果
Select stu_name, sum(decode(subject,'语文',score))语文,
sum(decode(subject,'数学',score))数学,
sum(decode(subject,'英语',score))英语
From stu_score Group By stu_name;
--统计有两门及两门以上不及格的同学及平均分,不及格科目。(主要是Having的使用)
Select stu_name,Avg(score)平均分,Count(Case When score<60 Then 1 End)不及格科目数 From stu_score
Group By stu_name Having Count(Case When score<60 Then 1 End)>=2;
-- 查出每个学生的最擅长的科目,注意:group by是先排序后分组
Select stu_name, max(score)最高分 From stu_score Group By stu_name;
Select t.stu_name,t.max_score,s.subject From (Select stu_name, max(score) max_score From stu_score Group By stu_name)t,stu_score s Where t.stu_name = s.stu_name And t.max_score = s.score;
--需要注意说明:当同时含有where子句、group by子句 、having子句及聚集函数时,执行顺序如下:
--执行where子句查找符合条件的数据;
--使用group by子句对数据进行分组;对group by子句形成的组运行聚集函数计算每一组的值;最后用having子句去掉不符合条件的组。
--having子句中的每一个元素也必须出现在select列表中。有些数据库例外,如oracle。
--having子句和where子句都可以用来设定限制条件以使查询结果满足一定的条件限制。
--having子句限制的是组,而不是行。where子句中不能使用聚集函数,而having子句中可以。