select tsClassId as 班级Id, 班级人数=count(*) from TblStudent group by tsClassId having count(*)>10 --不能使用“班级人数”列名,因为having在select之前执行 order by 班级人数 asc --order by在select之后执行,所以可以使用“班级人数”列名
--聚合函数 select max(tmath) as 最高分 min(tmath) as 最低分 avg(tmath) as 平均分 from TblScore
--子查询 select 最高分=(select max(tmath) from TblScore, 最低分=(select min(tmath) from TblScore, 平均分=(select avg(tmath) from TblScore --联合 select 名称='最高分',分数=max(tmath) from TblScore union all select 名称='最低分',分数=min(tmath) from TblScore union all select 名称='平均分',分数=avg(tmath) from TblScore
向表中插入多条数据
使用union all插入多条数据。
--插入3条记录 insert into TblStudent select 'name1','男','address1','phone1',18,'birthday1','code1',3 union all select 'name2','男','address2','phone2',19,'birthday2','code1',2 union all select 'name3','男','address3','phone3',20,'birthday3','code1',1
在使用union进行插入数据的时候,也要注意union会去除重复的。
--只成功插入一条数据,因为union去除了重复数据 insert into TblStudent select 'name1','男','address1','phone1',18,'birthday1','code1',3 union select 'name1','男','address1','phone1',18,'birthday1','code1',3 union select 'name1','男','address1','phone1',18,'birthday1','code1',3 union select 'name1','男','address1','phone1',18,'birthday1','code1',3 union select 'name1','男','address1','phone1',18,'birthday1','code1',3
select * into TblStudent20190506Backup from TblStudent
注意:select into语句不能重复执行,因为每次执行都会创建一个新的表。
备份表结构
只拷贝表结构,不拷贝数据。
select top 0 * into TblStudent20190506Backup from TblStudent select * into TblStudent20190506Backup from TblStudent where 1<>1 --不建议使用
向表中数据插入另一个表
基本语法:insert into 表A select … from 表B
insert into TblStudent20190506Backup select tsname,tsgender,tsaddress,tsphone,tsage,tsbirthday,tscardid,tsclassid --自动编号列不需要插入 from TblStudent where tsgender='女'