1、保存数据文件至对象
select top 1000 * into temp
from _tianyaPWD
order by newid()
2、选择
select * from Student order by sdept,sage desc
--前者升序,后者降序
等于:select * from Student order by sdept,-sage
3、count语句等聚集函数
默认选择all,不取消重复值
select count(distinct sage) from Student
select avg(grade) from Sc where cno=1
多重条件语句:
select sum(ccredit) from sc,course
where sno='201215012' and sc.cno=course.cno
这里选择条件来自两个表,由于sno是sc表独有的列名,所以不需要加上前缀
第二个判断条件就是cno属性需要相同
4、groupby 语句
语句构造:一般按照某个属性分组,将其选出并得到某些统计值,加上分组信息
选择条件
绿色字段要相同
select cno,count(sno) from sc group by cno
错误查询:
select sno,avg(grade)
from sc
where avg(grade)>=90
group by cno
正确语句:
select sno,avg(grade)
from sc
group by sno
having avg(grade)>=70
5、连接查询
select student.*,sc.*
from student,sc
where Student.sno=sc.Sno
选择输出语句,sname属于student独有
select student.sno,sname
from student,sc
where Student.sno=sc.Sno and sc.Cno=2 and sc.Grade=90
自身连接:
select * from dbo.Course FIRST ,dbo.Course SECOND—创建别名
select FIRST.cno,SECOND.cno
from Course FIRST,course second
where first.cpno=second.cno
可能出现的错误:MS SQL 错误:无法绑定由多个部分组成的标识符 "xxxxx"
解决方案:https://yq.aliyun.com/articles/33906
6、查询以及模糊查询
、1查询成绩不及格的同学
select distinct sno
from sc
where grade<60
between and 语句,前小后大
select *
from student
where sage --not
between 20 and 23
等同于:
select *
from student
where sage in (20,22,23)
模糊匹配:
执行数据库查询时,有完整查询和模糊查询之分。
一般模糊语句格式如下:
SELECT 字段 FROM 表 WHERE 某字段 LIKE 条件;
- 1
其中,关于条件,SQL提供了四种匹配模式:
可以匹配任意类型和任意长度的字符,有些情况下若是中文,请使用两个百分号(%%)表示。
select * from Student where sno like '2012%'
将会把Student这张表里面,列名sno中含有以“2012”的记录全部查询出来。
select * from Student where sno like '%2002%' and sname like '%张%'
则可以查询出来所有包含sno包含2002字段 姓名包含‘张’字段的所有内容,所在的前后位置无所谓。
查询错误:
消息 208,级别 16,状态 1,第 1 行 对象名 'S' 无效
出错信息:
消息 208,级别 16,状态 1,第 1 行 对象名 'S' 无效
解决方法:
查询窗口上方工具栏有个下拉框,一定要在其内选中要查询的数据库,不是在左侧的浏览窗口选中。
匹配单个任意字符,它常用来限制表达式的字符长度
select sname,sno,ssex
from student where sname like '刘_'
只能找到“刘x”这样sname为两个字的内容。
指定一个字符、字符串或范围,要求所匹配的对象为他们中的任一个。
select * from student where sname LIKE'[王李张]_';1
李勇、王敏、张立等三个对象信息
如[]内有一系列字符(01234,abcde之类的)则可略写为“0-4”,“a-e”:
select * from student where sage like '2[0-3]'
其取之和[]相同,但它所要求匹配对象为指定字符以外的任一个字符。
select * from student where sname LIKE'[^王李张]_';
将找出不是姓氏为王李张的信息。
由于通配符的缘故,导致查询特殊字符“%”、“_”、“[”的语句无法正常实现,把特殊字符用“[]”括起来便可以正常查询。
select cno,ccredit from course
where cname like 'DB\_Design' ESCAPE'\'—ESCAPE表示‘\’是转义字符