数据分组
- 分组也可以按多来分组(先按一个分组后再按另一个分组)
- grounp by 语句
--从学生表中查询出每个班的班级id和班级人数
select
ClassId as 班级id,
班级人数=count(*)
from tblstudent
group by ClassId
--从学生表中查询出每个班的班级id和班级中的男同学的人数
select
ClassId as 班级id,
男同学的人数=count(*)--4
from TblStudent --1
where Gender='男'--2
group by ClassId--3
当使用分组或者聚合函数时,在select 查询列表中包含的列要么在分组中存在,要么这列包含在聚合函数中
- having语句——对分组后的每一组数据进行筛选
where语句是对原始数据的每一行进行筛选
select
ClassId as 班级id,
班级人数=count(*)
from tblstudent
group by ClassId
having count(*)>3
- SQL语句执行顺序
数据类型转换
- cast语句
--cast(表达式 as 数据类型)
select 100.0 +cast('1000' as int)
- convert语句
--convert(数据类型,表达式)
select 100.0+convert(int,'1000')
--转换日期
print getdate()
print convert(varchar,getdate(),120)
union的使用
- 联合结果集union(集合运算符)
select id,name from TblStudent
union all--不去除重复,对结果不会进行重新排列
select id,name from TblScore
select id,name from TblStudent
union --去除重复,对结果会进行重新排列
select id,name from TblScore
若将一个查询作为子查询或者作为另外一个查询一部分使用时,次查询不能使用order by 语句
一次插入多条数据
- 使用 union all 向表中插入多条数据
--使用union all向表中插入多条数据
select * from TblStudent
insert into TblStudent
select '陈琴','男','山西',53,10.22,'23',6
union all
select '陈棋','女','陕西',54,11.22,'24',5
union all
select '陈书','男','北京',55,12.22,'25',7
union all
select '陈画','女','上海',56,10.23,'26',4
若使用union向表中插入多条数据时,也会去除重复
- 将一张表中的数据全部拷贝到另一张新表中
--将一个表中的数据全部拷贝都一个新表中
--但原表中的约束不会出现在新表中
select * into TblStudent2 from TblStudent
- 只拷贝表的结构,不拷贝表的数据
--只拷贝表的结构,不拷贝表的数据
select top 0 * into TblStudent3 from TblStudent
select * from TblStudent3
- 给原本存在的表中追加另一个表中的数据
--给原本存在的表中追加另一个表中的数据
--使用insert into 表 select...from 表
insert into TblStudent3
select Name,Gender,Address,Age,Birthday,CardId,ClassId
from TblStudent where Gender='女'
字符串函数
- 1.len() 计算字符的个数
--1.len() 计算字符的个数
print len('Hi~最近好吗?')--8
--datalength()返回所占字节的个数,这个不是字符串函数
print datalength('Hi~最近好吗?')--13
print datalength(N'Hi~最近好吗?')--16,使用unico每个字符都占两个字节
- 2.大小写转换
--2.大小写转换
print upper('hello,how are you ?')--转换大写
print lower('HELLO,HOW ARE YOU?')
- 3.去掉两端空格
--3.去掉两端空格
print '========'+' hello '+'========='
print '========'+ltrim(' hello ')+'========='
print '========'+rtrim(' hello ')+'========='
print '========'+rtrim(ltrim(' hello '))+'========='
- 4.字符串截取函数
--4.字符串截取函数
--4.1 left() 从左边开始截取
print left('大家好,我是哈哈!!!',4)
--4.2 right() 从右边开始截取
print right('大家好,我是哈哈!!!',4)
--4.3 substring() 从哪一位开始截取几个
print substring('大家好,我是哈哈!!!',1,4)--大家好,
print substring('大家好,我是哈哈!!!',0,4)--大家好
print substring('大家好,我是哈哈!!!',-1,4)--大家 开始位置为-1表示从-1位开始截取4个
日期函数
- 1.getdate sysdatetime 获取当前时间
- 2.dateadd() 增加时间
--dateadd() 增加时间
select dateadd(day,200,getdate())
- 3.datediff()计算两个日期的差
--datediff()计算两个日期的差
select datediff(year,' 1996-10-22',getdate())
- 4.datepart() 获取日期的某部分,为数字表现形式
--datepart() 获取日期的某部分,为数字表现形式
print datepart(year,getdate())
print datepart(dayofyear,getdate())--获取当前日期是这一年中的第几天
print year(getdate())--年,月,日有简便方法
- 5.返回日期的某部分,为字符串表现形式
--返回日期的某部分,为字符串表现形式
print datename(year,getdate())