SQL server条件以及高级查询
--条件
--where 请问if()
--select,update,delete需要加条件
--true flase
--关系运算符: && || !
--> < = >= <= != and or not
select *from student
select *from student where saddress='陕西'
select *from student where sid=2
select *from student where sid>=2
select *from student where sid<=2
select *from student where sid<2
delete from student where sid=1
update student set sname='刘德华' where sid=2
select *from student
--聚合函数
--只显示一行
--SUM(字段名) 把数据栏的值相加
--AVG(字段名) 得出一个表格栏平均值
--COUNT(*;字段名) 对数据行数的统计或对某一栏有值的数据行数统计
--MAX(字段名) 取得一个表格栏最大的值
--MIN(字段名) 取得一个表格栏最小的值
--引用以上函数方法:select函数(字段名)as 别名from 数据表where 条件表达式
select sum(sid) 总和,avg(sid)平均值,max(sid)最大值,min(sid)最小值,count(sid)总行数from student
--top(n):只显示前n行
select top(2)*from student order by sid
--groupby 分组
select * from students
insert into students values(5,'李四','山西')
insert into students values(6,'李四','陕西')
insert into students values(7,'李四','山西')
insert into students values(8,'李四','海南')
insert into students values(9,'李四','海南')
select * from students
select saddress,count(saddress),sum(sid),avg(sid),max(sid),min(sid) from students group by saddress
--高级查询
--连接查询
--内连接
--外连接
--left join 左外连接:左外连接(左连接):结果集既包括连接表的匹配行,也包括左连接表的所有行。
--right join 右外连接:右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
--full join 全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
select s.sname,c.cname from students s innerjoin cls c on s.cid=c.cid
select s.sname,c.cname from students s left join cls c on s.cid=c.cid
select s.sname,c.cname from students s rightjoin cls c on s.cid=c.cid
select s.sname,c.cname from students s full join cls c on s.cid=c.cid
--模糊查询
--like
--% 不限个数不限内容
--_ 一个字符不限内容
--[] 一个字符限制内容
select * from titles where title like '%Busy%'
select * from titles where title like 'The Psychology of Computer Cookin_'
select * from titles where title like 'The [BGP]%'
--记录合并查询
--union all
/*UNION 运算符通过组合其他两个结果表(例如TABLE1 和TABLE2)
并消去表中任何重复行而派生出一个结果表。当ALL随UNION一起使用时(即UNIONALL),
不消除重复行。两种情况下,派生表的每一行不是来自TABLE1就是来自TABLE2。
*/
select * from titles
union
select * from titles
union
select * from titles
select * from titles
union all
select * from titles
union all
select * from titles order by price
--子查询嵌套查询
/*子查询
(表名:a 表名:b)
select a,b,cfrom a where a IN (select d from b 或者:select a,b,c from a where aIN (1,2,3)
*/
select cid from cls where cname='net'
select *from students wherecid=10001
select *from students wherecid=(select cidfrom cls wherecname='net')
--集合查询法
--in
--not in
--all
--any
select * from students wherecid in(10002,10001)
select * from students wherecid in(selectcid from cls)
select * from students wherecid not in(select cid from cls)
select * from students wherecid >
all(select top 2 cid from cls)
select * from students wherecid > any(select top 2 cid from cls)