SQL 如何将一个表中的两条或多条拥有相同ID的记录合并为一条?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 如何将一个表中的两条或多条拥有相同ID的记录合并为一条?相关的知识,希望对你有一定的参考价值。
例:表A中有列和数据:
Col1 Col2 Col3 Col4
1 a b NULL
2 a1 b1 NULL
2 a1 NULL c1
合并效果为:
Col1 Col2 Col3 Col4
1 a b NULL
2 a1 b1 c1
一、创建表:
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
如果你要是 把上面的数据生成新的数据插入到表中的话...就直接插入操作.
希望能帮到你吧! 参考技术B select distinct * into temp_table from table_name
go
delete from table_name
go
insert into table_name select * from
go追问
您的意思是:查询语句是排除相同的记录插入临时表temp_table,删除原有表table_name的记录,最后查出temp_table中的记录插回table_name表中?
我的问题不是这个意思哦!而且我的表中没有重复的记录!不过还是谢谢!
如果只是上面的这种数据可以这样来实现
select col1,max(col2) as col2,max(col3) as col3,max(col4) as col4 from table group by col1本回答被提问者采纳 参考技术D 怎么解决的,我也遇到这种情况了,帮帮忙哈
ORACLE SQL语句查询一个字段在另一表字段中有两条或以上 的数据
如题:有A表,和B表,A表中的student是唯一,B表中的student不唯一,查询出来A表中哪些数据在B表中是多条而不是单条的!求解,感激不尽!
1、创建两张测试表,
create table test_student(student_id varchar2(20), student_name varchar2(20));
create table test_class(student_id varchar2(20), class_id varchar2(20));
2、插入测试数据
insert into test_student values(1001,'陈XX');
insert into test_student values(1002,'许XX');
insert into test_student values(1003,'张XX');
insert into test_student values(1004,'吴XX');
insert into test_class values (1001,'C01');
insert into test_class values (1001,'C02');
insert into test_class values (1002,'C01');
insert into test_class values (1003,'C01');
insert into test_class values (1004,'C01');
insert into test_class values (1004,'C02');
3、查询表的记录,select t.*, rowid from test_class t;
4、编写sql,查询出来test_student表中在test_class表中是多条而不是单条的记录,可以看到1001、1004学生是有多条记录的,
select t.student_id,
count(1) a
from test_student t , test_class b
where t.student_id = b.student_id
group by t.student_id
having count(*)>1,
参考技术A -- 先取并集,然后查询student2是否两条(根据id排序)SELECT student FROM (SELECT student FROM A union SELECT student FROM B) a1,A a2 WHERE a2.student=a1.student and (SELECT count(*) FROM B GROUP BY student) >= 2;
-- 或者
SELECT * FROM A a, B b WHERE a.student=b.student ORDER BY b.student HAVING COUNT(*)>=2;本回答被提问者采纳 参考技术B select b.student ,count(1) from b,a where b.student =a.student group by b.student having count(1) >1;
以上是关于SQL 如何将一个表中的两条或多条拥有相同ID的记录合并为一条?的主要内容,如果未能解决你的问题,请参考以下文章