创建数据库、创建学生表并设置主键、插入数据代码如下:
--创建数据库
create database StudentMS
--使用数据库
use StudentMS
--创建学生表 (属性:姓名、学号(pk)、学院、出生日期、性别、籍贯)
create table xs
(
name varchar(10) not null,
id varchar(10) not null,
xy varchar(10),
birthday datetime,
xb char(2),
jg varchar(8)
)
--创建学生表主键:学号
alter table xs
add constraint
pk_xs primary key(id)
--插入数据
insert into xs
(id, name, xb, birthday, xy, jg)
values('1160001', '刘备', '男', '1991-11-5', '软件学院', '河北省');
输出数据如下图所示:
2.子查询统计不同性质的学生总数
使用子查询统计不同学院总人数、不同性别总人数和河北/河南学生总人数。
--子查询统计人数
select a.a_num as 软院人数, b.b_num as 计院人数, c.c_num as 自动化人数,
d.d_num as 男生人数, e.e_num as 女生人数, f.f_num as 河北河南人数
from
(select count(*) as a_num from xs where xy='软件学院') a,
(select count(*) as b_num from xs where xy='计算机学院') b,
(select count(*) as c_num from xs where xy='自动化学院') c,
(select count(*) as d_num from xs where xb='男') d,
(select count(*) as e_num from xs where xb='女') e,
(select count(*) as f_num from xs where jg in ('河北省','河南省')) f;
输出结果:
3.一行数据转换成两列数据
这时,项目SQL语句的需要是显示成两列如下图所示:
select '软院人数' as "统计类别", count(*) as "数量" from xs where xy='软件学院'
union all
select '计院人数', count(*) from xs where xy='计算机学院'
union all
select '自动化人数', count(*) from xs where xy='自动化学院'
union all
select '男生人数', count(*) from xs where xb='男'
union all
select '女生人数', count(*) from xs where xb='女'
union all
select '河北河南人数', count(*) from xs where jg in ('河北省','河南省');
select whxs1.num1 as 项目名称, whxs2.num2 as 数量
from
(select decode(KWHD_WH_XZ, '校级', '校级总数', KWHD_WH_XZ) as num1
from T_WSTB_KWHD_1 t
where KWHD_WH_XZ='校级'
group by KWHD_WH_XZ) whxs1,
(select sum(decode(t.KWHD_WH_XZ,'校级',1,0)) as num2
from T_WSTB_KWHD_1 t
where KWHD_WH_XZ='校级'
group by KWHD_WH_XZ ) whxs2;
输出如下,但是再添加一行数据如何实现呢?所以还是推荐UNION ALL。
4.表行列数据转换(表转置)
参考:http://blog.163.com/dreamman_yx/blog/static/26526894201121595846270
select country, sum(case when type='A' then money end) as A,
sum(case when type='B' then money end) as B,
sum(case when type='C' then money end) as C
from table1
group by country
decode(条件,值1,结果1,值2,结果2,值3,结果3,... 值n,结果n,缺省值)
函数类比:
IF 条件=值1 THEN
RETURN(结果1)
ELSIF 条件=值2 THEN
RETURN(结果2)
......
ELSIF 条件=值n THEN
RETURN(结果n)
ELSE
RETURN(缺省值)
END IF
举个例子如下:
select
name as 姓名,sum(decode(t.result,'胜',1,0)) as 胜,sum(decode(t.result,'负',1,0)) as 负
from t_result t
group by name
order by 胜 desc,负 asc