mssql学习笔记【1】

来源:互联网 发布:北京市劲松职高网络 编辑:程序博客网 时间:2024/06/06 12:33

使用smalldatatime类型数据 将显示:  年-月-日 时:分:秒


use s
select * from test 

*号表示查每个元组的所有列


select count (*)  number from test where sdept like'计算机'

查计算机系学生人数,count()计数函数 上述 count(字段名) 和count(*) 效果一样

 

select count(sdept) number from test

返回test表中的所有记录条数  上述 count(字段名) 和count(*) 效果一样


select distinct * from test

distinct 关键字去掉重复的列


select sum(sage)   sumsage from test


sum函数求和 处理目标只能是数字类型  对char 或者varchar不能处理

select sum (sage) jsjage from test where sdept like '计算机'


avg返回平均值,处理目标只能数字类型
 
select avg(sage)  avgSage from test


max min 最大最小值  不能 用于where字句中,只能用子查询,但可以对字符串数据操作

select max(sage) maxsage from test

select min(sage) minsage from test


日期、时间 数学 字符串 函数 书 P77-85

select getdate()
获取当前时间 精确到毫秒


查询:

主要字句

select

into

from

[where  ]  用于限制选取的记录条件

[group by  ]  加分组关键字  用于将查询的结果按某一字段进行分组显示

[having   ]   加条件  用于对分组进行条件限制  

[order by  asc|desc   ]  加排序关键字 用于将查询结果按某一字段进行升序或者降序排列 asc升序 desc降序


select 列名列表

from  表名/试图表名

group by 列名 聚合函数

having 条件分组

order by 列名 [asc|desc]

 先 where  再 group by 再 having 再 select 后 order

有join字句的select 先join 再 where  再 select


单列 查询所有学生的姓名  要求预先知道表的结构和字段名

select sname

from s


多列查询 重新指定列名 和顺序

select sname 姓名,sgentle 年龄, sdept 部门
from s


为学分加1 指定新列名  表中的实际数据还是没变 因为select不是操纵sql语句
select cno 课程号 ,cname 课程名称,cgrade+1  学分
from c


查询左右列 不能指定新列名

select  *
from s


distinct all  关键字  默认是all

select distinct cgrade

from c

select cgrade

from c

 

top关键字

top n 返回前n跳记录
top n percent  返回前百分之n的数据

select top 3 sno 学号,sname 学生姓名, sage 学生年龄,sdept 学生所在系
from s

select top 1 percent *
from s

select top 100 percent *
from s


into 字句
把查询结果放到一个新建的表中 select into 不能与 compute 字句一起使用

select sname,sgentle,sage,sdept
into newS
from s
select *
from news


下面必须要指定新列名了
select sname,sage+10  newSage,sgentle,sdept,sno
into newS2
from s
select *
from news2

into创建的是基表 使用灵活

将学生表数据复制到stu表中
select *
into stu
from s
select *
from stu

 


from 子句
from字句最多可接256个表或试图中间用逗号隔开

表的别名
例:
select sno,sname,sage
from s s1
生成一个三列的s1新表 注意但不时基表

 

 

原创粉丝点击