四时宝库

程序员的知识宝库

SQL Server常用的函数总结1(sqlserver数据库函数)

Top、Distinct函数

Top函数:

使用Top函数,可以只返回结果集的前N条记录【N可以是数值,百分数等】。

注意:记录显示的值是进1制而不是四舍五入。

Bash
select top 10 * from Teacher --前10条记录
select top 10 percent * from Teacher --前10%条记录,此时记录显示的值是进1制而不是四舍五入

Distinct函数:

distinct函数主要用于去除重复值,他的作用与原始记录表的数据无关,只与当前的结果集有关系,处理查询出来的结果集。

Bash
select Name ,Age from Teacher
select distinct Name,Age from Teacher

NULL空值处理:

NULL:表示不知道,而不只是表示空值。

例如:查询没有工资的老师信息。

Bash
use TestSchool
select * from Teacher where Salary is not null

isNull: 如果发现对应的值是Null值,则以指定的字符串文本进行替换

Bash
select Name ,Age ,ISNULL(Salary ,NULL) from Teacher

union函数--集合运算符

union(联合):用来联合多个结果集的,叫做集合运算符。

注意:

1、要求联合的的多个结果集有相同的数量的字段

2、要求联合的多个结果集对应的列的数据类型一致(可以相互转换)

Bash
select count(*) from Teacher where Gender = 'False'
union all 
select count(*) from Teacher where Gender = 'True'

union 和union all 的区别:

union 默认是去除重复值的,效率低,是因为需要为你做是否重复的判断

union all --不去除重复项

注意:

使用union all一次性插入多条记录

Bash
insert into Classes
select 1,023班 union 
select 4,026班 union all 
select 5 ,027班 union 
select 5,027班 

注意:只要有 union 联合时,去除插入记录重复值。

Bash
insert into Classes
select 1,023班 union all
select 4,026班 union all 
select 5 ,027班 union all
select 5,027班 

注意:只有全部都用 union all 联合时,不去除重复值。

select into from:

可以将from数据源表中的select指定的列的数据 into到新表中,新表是系统自动生成的,不能先人为创建,也就不能先存在。新表中,列的属性只保留标识列,其余均消失

Bash
select * into newtable From Classes
insert into newtable select Cid,CName from Classes

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接