Home  >  Article  >  Database  >  SQL 合并多行记录的相同字段值

SQL 合并多行记录的相同字段值

WBOY
WBOYOriginal
2016-06-07 18:00:041040browse

有时候会遇到这种情况,数据库查询返回多行记录,且每行记录由另外符合条件的多条记录内容合并,遇到这种情况,我们可以选择下面两种方式

1.从数据库中先查询符合条件的记录,存放于一个DataTable中,在使用c#等开始遍历这张表,利用DataRow中的主键,再去读取相应的符合条件的多条记录,合并这些第二次读取到的记录内容,返回给前面的这个DataRow数据行。这样做没有错,但是如果数据量大,我们可能面临无数次的打开断开数据库链接,速度效率将会很低。
2.从数据库中一次读取数据到一张表中返回并显示到UI层。说起来谁都想这么做,但是以前太笨,没有去研究这个,今天因为数据量较大的原因,让我不得不想些其他办法来提高点效率。
Google~hk一下,果真有答案,然后依葫芦画瓢,自己写了一个
目的是获取不定量的符合条件的兼职记录,并将每个兼职参与项目情况记录到某几个字段当中,然后一次返回Table
代码如下:
Create function Fn_GetJobListByPID--创建自定义函数获取指定兼职参与的所有项目编号及项目数量
(
@ParttimerID int
)
returns @t table(Jobs varchar(5000),ParttimerID int,TotalCount int)
as
begin
declare @sql varchar(5000),@TotalCount int
set @sql=''
set @TotalCount=0
select @sql=@sql+j.JobNo+'-'+j.JobWave+' ',@TotalCount=@TotalCount+1
from ONJB_JobApplication a,ONJB_Jobs j
where a.ParttimerID=@ParttimerID
and a.Result='V'
and a.JobID=j.JobID
insert @t values(@sql,@ParttimerID,@TotalCount)
return
end

引用
代码如下:
--...........................
--做过项目
left join (select Jobs,ParttimerID,TotalCount From Fn_GetJobListByPID(@ParttimerID)) as j1
on p.ParttimerID=j1.ParttimerID
--在做项目
left join (select CurJobs,ParttimerID,CurCount From Fn_GetCurJobsByPID(@ParttimerID)) as j2
on p.ParttimerID=j2.ParttimerID
where p.ParttimerID=@ParttimerID
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn