拼接字段:将值连接到一起构成单个值,使用concat()函数来拼接两个列。
select concat(name,'(',country,')') from student order by name
concat()拼接串,即把多个串连接在一起来形成一个较长的串,concat()需要一个或多个指定的串,各个串之间用逗号分隔开。
select concat(RTrim(name),'(',RTrim(country),')') from student order by name
RTrim()函数去掉右边的所有空格,通过RTrim()函数,各个列都进行了整理。
LTrim()函数去掉串左边的空格以及Trim()去掉串左右两边的空格。
使用别名:as
select concat(RTrim(name),'(',RTrim(country),')') as title from student order by name
别名的其他用途:在实际的表列名包含不符合规定的字符时重新命名它,在原来的名字混或容易误解时扩充它。
数据处理函数
文本处理函数 select name ,Upper(name) as namespace from student order by name
upper()函数将文本转换为大写,与之对应的是小写lower()
常用的文本函数:
Left() 返回串左边的字符串
Length() 返回串的长度
Locate() 找出串的一个子串
Ltrim() 去掉串左边的空格
Rtrim() 去掉串右边的空格
Soundex() 返回串的soundex值 是一个将任意文本串转换为描述其语音表示的字母数字模式的算法
Substring() 返回子串的字符
Upper() 将串转换为大写
日期和时间处理函数
AddDate() 增加一个日期(天,周等)
AddTime() 增加一个时间(时,分等)
CurDate() 返回当前日期
CurTime() 返回当前时间
Date() 返回日期时间的日期部分
DateDiff() 计算两个日期只差
Date_Add() 高度灵活的日期运算函数
Date_Format() 返回一个格式化的日期或时间串
Day() 返回一个日期的天数部分
DayOffWeek() 对于一个日期,返回对应的星期几
Hour() 返回一个时间的小时部分
Minute() 返回一个时间的分钟部分
Month() 返回一个时间的月份部分
Now() 返回当前日期和时间
Second() 返回一个时间的秒部分
Time() 返回一个日期时间的时间部分
Year() 返回一个日期的年份部分
例: select birthday from student where birthday='1995-07-17'
例: select order from orders where Date(order_date)='2015-09-01' 如果想要的仅是日期,则使用Date()是一个良好的习惯
日期时间段匹配:select order from orders where Date(order_date) between '2015-09-01' and '2021-06-09'
另一种匹配方式: select order fron orders where Year(order_date)=2015 and Month(order_date)=9
数值处理函数
Abs() 返回一个数的绝对值
Cos() 返回一个角度的余弦
Exp() 返回一个数的指数值
Mod() 返回除操作的余数
Pi() 返回圆周率
Rand() 返回一个随机值
Sin() 返回一个角度的正弦
Sprt() 返回一个数的平方根
Tan() 返回一个角度的正切
聚集函数:计算在行组上,计算并返回单个值的函数。
常见的聚集函数有:
avg() 返回某个列的平均值
count() 返回某个列的行数
max() 返回某个列的最大值
min() 返回某个列的最小值
sun() 返回某列之和
例:select avg(sage) as '年龄' from student
select count(sno) as '学号' from student
select max(credit) as '最高学分',min(credit) as '最低学分' from course
select sum(*) from student
分组数据:group by
group by 子句必须出现在where子句之后,order by之前。
使用with rollup关键字,可以得到每个分组以及每个分组汇总级别的值。
例:select sno ,count(*) as 'info' from student group by sno
过滤分组:hanving
having与where:where过滤行,having过滤分组,where在数据分组前过滤,having在数据分组后过滤。
select cno,count(*) as 'cinfo' from sc group by cno having count(*)>2