sql合并函数
1. sql 如何将一个表中的两条或多条拥有相同ID的记录合并为一条
一、创建表:
create table stuUnion
(
sid int identity primary key,
cid int,
id varchar(500)
)
二、添加数据:
insert into stuUnion
elect 1,'a' union
select 1,'b' union
select 2,'c' union
select 2,'d' union
select 3,'e' union
select 3,'f' union
select 3,'g'
三、用标量函数查询:
创建标量函数:
create function b(@cid int)
returns varchar(500)
as
begin
declare @s varchar(500)
select @s=isnull(@s+'','')+rtrim(id)+',' from stuUnion where cid=@cid
return @s
end;
用标量函数查询:
select cid,dbo.b(cid) as id from stuUnion group by cid
用sqlserver的xml:
select cid,ID=STUFF((select ' '+rtrim(id)+',' from stuUnion where st.cid=cid order by id for XML path('')),1,1,'') from stuUnion st group by cid
2. sql 语句中那些是聚合函数
常见聚合函数,max(最大)、min(最小)、sum(求和)、avg(平均)等,
示例如下亮旦扒,
1、创建测试表,
create table test_group(id number, value number);
3. SQL怎么拼接字符串
不同的数据库,相应的字符串拼接方式不同,通过对比加深一下记忆。
一、MySQL字符串拼接
1、CONCAT函数
语法格式:CONCAT(char c1, char c2, ..., char cn) ,其中char代表字符串,定长与不定长均可以
连接两个字符串
(3)sql合并函数扩展阅读
字符串函数(String processing function)也叫字符串处理函数,指的是编程语言中用来进行字符串处理的函数,如C,pascal,Visual以及LotusScript中进行字符串拷贝,计算长度,字符查找等的函数。
字符串主要用于编程,概念说明、函数解释、用法详述见正文,这里补充一点:字符串在存储上类似字符数组,所以它每一位的单个元素都是可以提取的,如s=“abcdefghij”,则s[1]=“a”,s[10]="j"。
而字符串的零位正是它的长度,如s[0]=10(※上述功能Ansistring没有。),这可以给我们提供很多方便,如高精度运算时每一位都可以转化为数字存入数组。
字符串函数的应用
1、连接运算 concat(s1,s2,s3…sn) 相当于s1+s2+s3+…+sn.
例:concat(‘11’,'aa’)='11aa’;
2、求子串。 Copy(s,I,I) 从字符串s中截取第I个字符开始后的长度为l的子串。
例:(‘abdag’,2,3)=’bda’
3、删除子串。过程 Delete(s,I,l) 从字符串s中删除第I个字符开始后的长度为l的子串。
例:s:=’abcde’;delete(s,2,3);结果s:=’ae’
4、插入子串。 过程Insert(s1,s2,I) 把s1插入到s2的第I个位置
例:s:=abc;insert(‘12’,s,2);结果s:=’a12bc’
5、求字符串长度 length(s) 例:length(‘12abc’)=5
在ASP中 求字符串长度用 len(s)例: len("abc12")=5
6、搜索子串的位置 pos(s1,s2) 如果s1是s2的子串 ,则返回s1的第一个字符在s2中的位置,若不是子串,则返回0.
例:pos(‘ab’,’12abcd’)=3
7、字符的大写转换。Upcase(ch) 求字符ch的大写体。
例:upcase(‘a’)=’A’
8、数值转换为数串。 过程 Str(x,s) 把数值x化为数串s.
例:str(12345,s); 结果s=’12345’
9、数串转换为数值。 过程val(s,x,I) 把数串s转化为数值x,如果成功则I=0,不成功则I为无效字符的序数,第三个参数也可不传
例:val(‘1234’,x,I);结果 x:=1234
4. sql如何将二个字段连接在一起
方法一:
sql中的连接符用“||”;
举例1:select 'zhang'||' san' from al ;结果就是 “zhang san”;
举例2:select name || '的年龄是'|| age from tablename;结果就是“zhangsna的年龄是11”。
方法二:
mysql, oracle db2
select field1 || field2 from tab
sql server:
select field1 + field2 from tab
SQL的核心部分相当于关系代数,但又具有关系代数所没有的许多特点,如聚集、数据库更新等。它是一个综合的、通用的、功能极强的关系数据库语言,尽管SQL的功能很强,但语言十分简洁,核心功能只用了9个动词。
(4)sql合并函数扩展阅读:
SqlServer函数
upper(char_expr) 转为大写
lower(char_expr) 转为小写
space(int_expr) 生成int_expr个空格
replicate(char_expr,int_expr)复制字符串int_expr次
reverse(char_expr) 反转字符串
stuff(char_expr1,start,length,char_expr2) 将字符串char_expr1中的从start开始的length个字符用char_expr2代替