select语句格式:
select select_list
from table_list
[where search_condition]
[group by group_by_list]
[having search_condition]
[order by order_list[asc|desc]]
如果没有order by 子句,系统默认是不排序的
select语句的执行顺序
1,from语句组装来自不同数据源的数据
2,where子句基于指定的条件对记录进行筛选
3,group by 子句将数据划分成多个组
4,使用聚合函数进行计算
5,使用having子句筛选分组
6,计算所有表达式
7,使用order by 子句对结果集进行排序
查询中使用别名的三种方式
原句:select sno,sname from student
1,使用 as
select sno as '学号',sname as '姓名' from student
2,直接跟在后面,省略 as
select sno '学号',sname '姓名' from student
3,使用 = ,注意别名在等号前面
select '学号'=sno,'姓名'=sname from student
消除重复数据 ---关键字distinct
select distinct name from grades
限定显示的行数---关键字top,配合order by 使用有很好的效果
使用固定数字:
select top 1 * from student ---只显示第一条记录
使用百分数
select top 5 percent * from student--显示前5%的数据
范围运算符 ---关键字 between...and
between ... and 和 not between and
用于测试给定的值是否在一个指定的范围内,between and 是闭区间
select * from grades where grade between 60 and 80--查找60到80分的成绩信息(含60,80分)
列表运算符 ---关键字 in
in 和 not in
在一个列表中查找是否有与给定的值精确匹配的值,有则返回true
select * from grades where grade in (70,80) --有没有刚好是70或者80分的成绩
等价于
select * from grades where grade = 70 or grade = 80
模式运算符 ---关键字 like
like 和 not like
判断列值是否和指定的字符串格式相匹配
可用于char、varchar、text、datetime等数据类型
空置运算符--关键字 is null
is null 和 is not null
=不能去检测空值null,所以使用is来检测
select × from student where sbirthday is null
如果用= null,系统不会报错,但是检测不到
排序 --关键字order by
如果不指定排序顺序,默认升序
order by 后面可以跟表达式,使用()可以使结构更清晰
使用多个排序点,以,号隔开
select * from grades order by cno asc,grade desc
一些函数
字符串函数 -----P108页
datalength(char_expr):返回字符串包含的字节数(包含后面的空格)
--一个汉字是两个字节,使用datalength可以检测
len(char_expr):返回字符串包含的字符数,不包含后面的空格
substring(expression,start,length):取得字字符串
upper/lower 转换成大/小写
ltrim/rtrim 清除字符串 左边/右边 的空格
日期和时间函数 ----P109
getdate() :取得系统当前日期
datename(datepart,date_expr) :取得日期中指定日期部分的字符串形式
datepart(datepart,date_expr) :同上,取得整数形式
日期部分有year,month,day,week,hour,minite,second,millisecond
dayofyear(第几日),weedday(周几)
日期部分都有缩写
系统函数
本文详细介绍SQL查询语句的构成及使用技巧,包括select语句的格式、执行顺序、使用别名的方法、消除重复数据、限定显示行数、范围运算符、列表运算符、模式运算符、空值运算符、排序方法及常用函数等。
991

被折叠的 条评论
为什么被折叠?



