SQLserver数据库的一些简单的操作2

转载请声明出处:https://blog.csdn.net/cyzhah/article/details/82312657

一、分组

1、select  tsClass as 班级id,班级人数 = count (*) from TblStudent group by tsClassid (从学生表查询出每个班的班级id 和班级人数)

2、select  性别 = tsgender,人数=count(*) from TbStudent group by tsClassid(统计所有学生中男同学与女同学的人数分别是多少)

3、select 班级Id = tsclassid,男同学人数 = count(*)from TbStudent where tsgender = '男' group by tsclassid(查询每个班的班级id和班级中男同学的人数)

4、对分组以后的数据进行筛选,使用having

select tsClassid as 班级id,班级人数 = count(*) from Tblstudent group by tsClassId having count(*)>10 order by 班级人数 asc

having 与 where都是对数据进行筛选,where是对分组前的每一行数据进行筛选,而having是对分组后的每一组数据进行筛选

5、统计销售总价超过3000元的商品名称和销售总价,并按销售总价降序排序

select

商品名称,销售总价 = sum(销售数量*销售价格)

from MyOrders

group by 商品名称

having sum (销售数量*销售价格)>3000

order by 销售总价 desc

6、统计各个客户对"可口可乐"的喜爱度(即统计每个购买人对"可口可乐"的购买量)

select 购买人,购买可口可乐数量 = sum(销售数量)

from MyOrders

where 商品名称 = ‘可口可乐’

group by 购买人

order by 购买可口可乐数量 desc

二、类型转换函数

select 100.0 + cast('1000' as int)

select 100.0 + convert(int,'1000')

三 、union 的使用(联合多个结果集的列的数目必须一致,且数据类型需要兼容)

1、union all 不会去除重复也不会重新排序,union会去除重复且重新排列

例子:

select tsname,tsgender , tsage from TbStudent

union all

select fname,fgender,fage from MyStudent

---------------------------------------------------------- ---------------------------------------------------------------------------

select tsname,tsgender , tsage from TbStudent

union 

select fname,fgender,fage from MyStudent

---------------------------------------------------------------------------------------------------------------------------------

查询成绩表中的最高分,最低分,平均分(三种写法)

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

2、使用union all 向表中一次性插入多条数据

insert  into TblStudent 

select  'xxxx' ,'xxxxxxxxx','xxxxxxxxxx','xxxx'

union all 

select  'xxxx' ,'xxxxxxxxx','xxxxxxxxxx','xxxx'

union all 

select  'xxxx' ,'xxxxxxxxx','xxxxxxxxxx','xxxx'

四、向表中插入多条记录

select  *  into  tbStudentCopy  from   tbStudent  

(从学生表中查询所有列并插入到tbStudentCopy)(相当于备份,但在第一张表中的约束不会一起拷贝过来)

1、拷贝表结构

select   top 0*  into  tbStudentCopy  from   tbStudent  (只把表结构拷贝到tbStudentCopy表中,数据是没有的)

select  into  tbStudentCopy  from   tbStudent where 1< >1 (和上面一样效果)

select  into  tbStudentCopy  from   tbStudent where 1==2 (和上面一样效果)

2、

猜你喜欢

转载自blog.csdn.net/cyzhah/article/details/82312657