SQL中常用函数总结

聚合函数

avg(): 函数返回组中各值的平均数

sum():函数返回组中各值之和

?
1
select sum(money) from cash

count():函数返回匹配指定条件的行数

count(column_name) 函数返回指定列的值的数目(NULL 不计入)

count(*) 函数返回表中的记录数

count(DISTINCT column_name) 函数返回指定列的不同值的数目

 

查询范围——orders表:

 

O_Id OrderDate OrderPrice Customer
1 2008/12/29 1000 Bush
2 2008/11/23 1600 Carter
3 2008/10/05 700 Bush
4 2008/09/28 300 Bush
5 2008/08/06 2000 Adams
6 2008/07/21 100 Carter

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
select count(*) N'Bush的订单总数' from orders
where cumstomer = 'Bush'
 
执行结果:3
 
select count(customer) from orders
where OrderPrice >= 1000
 
执行结果:3
 
select count(distinct customer) from orders
where OrderPrice <= 1000
 
执行结果:2

Max():函数返回表达式的最大值

Min():函数返回表达式的最小值

 

 

日期函数

getdate():函数返回当前时间

?
1
2
3
select getdate()
 
函数返回:2012-04-09 21:29:25.493

datepart(datepart, date):函数返回时间的某一部分

datepart的有效值如下:

datepart 缩写
yy, yyyy
季度 qq, q
mm, m
年中的日 dy, y
dd, d
wk, ww
星期 dw, w
小时 hh
分钟 mi, n
ss, s
毫秒 ms
微妙 mcs
纳秒 ns
?
1
select datepart(hh,getdate())

dateadd(datepart,number,date):函数在日期中添加或减去指定的时间间隔 date 参数是合法的日期表达式。number 是您希望添加的间隔数;对于未来的时间,此数是正数,对于过去的时间,此数是负数。

?
1
select dateadd(dd,3,getdate())

datediff(datepart, startdate, enddate):函数返回两个日期之间的天数

?
1
2
3
select datediff(dd,'2012-4-9','2012-4-10')
 
执行结果:1

Day():函数返回日期的”日”部分month():函数返回日期的”月”部分year():函数返回日期的”年”部分

?
1
  

数学函数

abs():函数返回绝对值ceiling():函数返回大于等于该数的最小整数floor():函数返回小于等于该数的最大整数rand():函数返回一个0-1之间的随机数round(value,decimals):函数将一个数value舍入精确到小数点后decimals位小数

?
1
2
3
select round(3.1234,3)
 
执行结果:3.123

字符串函数charindex(expression1, expression2[ , start] )函数返回子串在目标串中最先出现位置的index,expression1为子串,expression2为目标串

?
1
2
3
select charindex('ab','asdabdd')
 
执行结果:4

left(expression, number):函数返回目标串的左边指定长度的子串

?
1
2
3
select left('黎明',1)
 
执行结果:黎

right(expression, number):函数返回目标串的右边指定长度的子串

 

ltrim(expression):函数去除字符串左边的空格

rtrim(expression):函数去除字符串右边的空格

?
1
2
3
4
5
去除字符串两边的空格
 
select ltrim(rtrim('    春哥  '))
 
执行结果:春哥

substring(expression, start, length):函数返回目标串的一个子串,start为起始地址,length为子串的长度

?
1
2
3
select substring('不管你信不信,反正我信了',4,3)
 
执行结果:信不信

upper():函数将目标串中的所有字符转化为大写字母

lower():函数将目标串中的所有字符转化为小写字母

?
1
2
3
4
5
select upper('Just Do It')
select lower('Just Do It')
 
执行结果:JUST DO IT
         just do it

其他函数isnull(expression, value): 如果expression是null的话,则返回value值,否则返回expression

?
1
select isnull(name,N'匿名') 姓名 from T_Persons

newid():创建uniqueindentifer类型的唯一值,常用于生成主键,每次返回的值都不一样

?
1
2
insert into T_persons(id,name,age)
values(newid(),N'小强',22)

猜你喜欢

转载自netbabe.iteye.com/blog/1481351