前面学习了数据库的增删改查,这次学习一下函数的使用。
首先,话不多说,先新建一个表,并且加入数据
create table teacher(
id int primary key identity,
name varchar(50) not null,
gender varchar(3) not null,
age int not null,
email varchar(50),
);
insert into teacher values('小胡','男',19,'121.com');
insert into teacher values('小圈','女',15,'122.com');
insert into teacher values('小完','男',43,'123.com');
insert into teacher values('小和','女',16,'124.com');
insert into teacher(name,gender,age) values('小盒','女',36);
insert into teacher(name,gender,age) values('小明','男',26);
先查询一下没有Email的/有Email的
这里null值是不能用“=”做比较的要用is 是/is not 不是
select * from teacher where email is null;
select * from teacher where email is not null;
输出结果(左第一条代码,右第二条代码)
--SQl中还可以用多个条件,比如有名字和有或者没有Email/的
这里只能用or(或者)/and(并且)
select * from teacher where name is not null and email is not null;
select * from teacher where name is not null and email is null;
输出结果
去除某个列的重复值 distinct
去掉重复的性别
select distinct(gender) from teacher;
输出结果
-- 排序 order by 两种排序方式(默认为升序)
1.asc 升序 2.desc 降序
根据id升序
select * from teacher order by id asc;
输出结果
因为默认为升序,所以写不写asc都无所谓
根据年龄降序
select * from teacher order by age desc;
输出结果
-- top 取前几个数据
假设取前三个
select top 3* from teacher;
输出结果
也可以在后面加条件,取前三个年龄最大的
那么就要先排序了,因为是取前三,所以用降序
select top 3* from teacher order by age desc;
输出结果
函数以及方法
--查找特定字符的位置
select * from teacher where charindex('胡',name)!=0;
输出结果
后面不等于0是因为没有就等于0,不等于0就代表有
--len 字符的个数
select len('你好');
输出结果
查询名字是两个字的
select * from teacher where LEN(name)=2;
输出结果
-- 大写 upper 和小写 lower 函数
select UPPER('ewfew');
select LOWER('WDSWQS');
输出结果
--清除空格
1.ltrim 左 2.rtrim 右
select ltrim(' 你好');
select rtrim('你好 ');
输出结果
--取字符
1.rigth 右边取 2.left 左边取
select right('你好啊',1);
select left('你好啊',1);
输出结果
----替换 replace
将‘aabbcc'里的’bb‘替换成’ff‘
select replace('aabbcc','bb','ff');
输出结果
--绝对值
select abs(-1);
输出结果
--求整
1.向上 ceiling
在去小数点的基础上加1
2.向下 floor
在去小数点的基础上减1
3.四舍五入 round
小于5退1,大于并且等于5进1
select ceiling(1.9999999999999999);
select floor(1.99999999999999999999);
select round(1.3,0);
输出结果