日期:2014-05-17  浏览次数:20493 次

怎么样去合并数据??

create table #tt
(
  fid nvarchar(30),
  fname nvarchar(30),
  fbh nvarchar(30),
  frq datetime
)
insert into #tt
select 'A1013','AG-14339','制模','2012-10-09'
union all
select 'A1013','AG-14339','修边','2012-10-11'
union all
select 'A1013','AG-14339','小红','2012-10-12'



declare @sql nvarchar(4000)
 

set @sql = ' select distinct fid,fname,'

select @sql=@sql+' (case fbh when '''+fbh+''' then convert(varchar(10),frq,121) else null end ) as '''+fbh+''','
  from (select fbh from #tt ) a 

select @sql=left(@sql,len(@sql)-1) +' from #tt '
 
exec (@sql)





怎么使数据并为一行



 


------解决方案--------------------
SQL code
declare @sql nvarchar(4000)
 
set @sql = ' select fid,fname,'

select @sql=@sql+'MAX (case fbh when '''+fbh+''' then convert(varchar(10),frq,121) else null end ) as '''+fbh+''','
  from (select fbh from #tt ) a  

select @sql=left(@sql,len(@sql)-1) +' from #tt GROUP BY fid,fname'
 
exec (@sql)

/**
fid                            fname                          制模         修边         小红
------------------------------ ------------------------------ ---------- ---------- ----------
A1013                          AG-14339                       2012-10-09 2012-10-11 2012-10-12

(1 行受影响)
**/