您好,欢迎访问一九零五行业门户网

SQLserver中常用的函数及实例

聚合函数 as是可以起别名的,在select和from之间的是表示列名,可以不加单引号)(聚合函数 中的count不仅能 对数字进行操作 还能对字符型进行操作,其余的只能对数字操作 ) 最小值 select min ( jiage ) as 价格 from shuiguo -- 求最低价格 select min (
聚合函数
as是可以起别名的,在select和from之间的是表示列名,可以不加单引号)(聚合函数中的count不仅能对数字进行操作还能对字符型进行操作,其余的只能对数字操作)
最小值
select  min(jiage) as 价格 from shuiguo --求最低价格
select  min(jiage) as 价格 from shuiguo --求最低价格
最大值
select max(jiage) as 价格 from shuiguo --求最高的价格
总数
select count(*) from shuiguo--查表中一共有多少个数据
select count(*) from shuiguo where chandi like '海%'--产地是海开头的有几个
select count(distinct chandi) from shuiguo --去重之后查个数
平均值
select avg(jiage) as 平均价格 from shuiguo--求平均价格
总和
select sum(jiage) as 价格 from shuiguo --求总和
也可以并排一起写,如:
select count(name) as 水果个数 ,sum(jiage) as 价格总和 from shuiguo
字符串函数
select ascii('')--返回字符串首字母ascii编码
select * from haha where ascii(name)>200
select char(100)--将ascii代码转换成对应的字符(ascii码对应的类型是int)
select charindex('sdf','asdfg')--查找字符串,返回符合条件的首字母索引,索引从1开始,返回0表示没有找到
select left('asdfg',3)--从左往右截取字符串指定长度
--结果为(asd)
select right('asdf',3)--从右往左按指定个数截取长度
--结果为sdf
select len(' asd    ')--返回字符串长度,后面的空格不计算
select lower('asdf')--将大写字母转换成小写字母
select upper('asda')--将小写字母转换成大写字母
select ltrim ('     aaaaaaaaa    a')--去除字符串左边的空格,字符串中间的空格去不掉
select rtrim ('a              ')--去除右边的可空格
select replace(列名,替换前的内容,替换后的内容)--replace替换只是在显示的时候替换,对原数据不做修改
select replicate('asd',3)--replicate为复制,前面是要复制的内容,后面是要复制几次
select reverse(1123)--reverse为翻转
select space(7)--space表示打印空格,参数表示打印几个空格
select str(小数的原数据,字符串的长度,截取小数点后几位)--小数点也算一个字符  --select str(5672.1234,8,2)结果为5672.12
select stuff('asdfghjk',3,0,'12345')    表示的意思是:12345插在d之后,0表示fghjk不删除,如果是1则删除f,2删除fg,以此类推
select substring(列名,要截取开始的位数,截取几位)--要截取开始的位数的索引是从1开始
日期和时间函数
select dateadd(year, 1,'2003-12-3')--指定日期加入一个时间段
select datediff(yyyy,'2001-12-5','2012-12-12')--求时间差,可以指定类型来算
--年year 月month 日day 时huor 分minute 秒second
select datepart(mm ,'2013-1-15')  ----获取当前月,只是datename是返回的字符串型,detapart时返回的int型
select getdate() --获取服务器当前时间
select isdate('2014-11-12')--判断是否是时间如期,如果时间正确返回,错误返回
select year('2012-12-12')--select后可跟年、月、日
数学规范函数
ceiling()取上限,小数点后有值就进
floor()取下限,不管小数点后有没有值,都舍掉
power(3,2)--表示3的2次方
round(1.2345,0) 后面参数是代表四舍五入到小数点后第几位
sqrt()平方根
square()求平方
附加  group by 与order by的区别
【要区分group by 与 order by】
group by 函数的作用是分组
order by 函数的作用是排序
 组合
select banji from xinxibiao   group by banji--分组
select banji,count(*) from xinxibiao group by banji having count(*)>4--having后只能加聚合函数,having是针对统计好的结果进行筛选,所以使用having的前提必须使用group by
--顺序:先是where条件,没有where的找from,后是group by ,再是select后的条件,最后是having
select banji,count(*) from xinxibiao where yuwen>=75 group by banji order by count(*) desc--每个班级语文成绩大于的有几个人,班级并降序排列
select banji ,avg(yuwen) from xinxibiao group by banji--分组之后并求平均分
select banji as 班级 ,max(yuwen) as 语文,max(shuxue) as 数学,max(yingyu) as 英语 from xinxibiao group by banji  --求每班每科的最高分
其它类似信息

推荐信息