日期:2014-05-19  浏览次数:20579 次

如何将多条记录合成一条
如:
编号             姓名             日期                         时间                 时间    
60 小凤             2007-06-01             09:23     12:34
60 小凤             2007-06-01             13:23     20:05
60 小凤             2007-06-01             20:18    

合成的结果

60 小凤             2007-06-01             09:23     20:18


这个SQL查询需怎么写,请高手指点
               


------解决方案--------------------
create table temp0616(编号 int,姓名 varchar(20),日期 datetime,时间1 varchar(10),时间2 varchar(10))

insert temp0616 select 60, '小凤 ', '2007-06-01 ', '09:23 ', '12:34 '
union all select 60, '小凤 ', '2007-06-01 ', '13:23 ', '20:05 '
union all select 60, '小凤 ', '2007-06-01 ', '20:18 ',null

select 编号,姓名,日期,case when min(时间1) <min(时间2) then min(时间1) else min(时间2) end 时间1,case when max(时间1) <max(时间2) then max(时间2) else max(时间1) end 时间2 from temp0616 group by 编号,姓名,日期

drop table temp0616
------解决方案--------------------
或者:
declare @t table(编号 int, 姓名 varchar(10),日期 varchar(10),时间1 varchar(6),时间2 varchar(6))
insert @t
select 60, '小凤 ', '2007-06-01 ', '09:23 ', '12:34 ' union all
select 60, '小凤 ', '2007-06-01 ', '13:23 ', '20:05 ' union all
select 60, '小凤 ', '2007-06-01 ', '20:18 ', NULL

select 编号,姓名,日期,
时间1 = min(case when 时间1 < 时间2 then 时间1 else 时间2 end),
时间2 = max(case when 时间1 < 时间2 then 时间2 else 时间1 end)
from @t group by 编号,姓名,日期

/*结果
编号 姓名 日期 时间1 时间2
----------------------------------------------------
60 小凤 2007-06-01 09:23 20:18
*/
------解决方案--------------------
create table temp0616(编号 int,姓名 varchar(20),日期 datetime,时间1 varchar(10),时间2 varchar(10))
insert temp0616 select 60, '小凤 ', '2007-06-01 ', '09:23 ', '12:34 '
union all select 60, '小凤 ', '2007-06-01 ', '13:23 ', '20:05 '
union all select 60, '小凤 ', '2007-06-01 ', '20:18 ',null


select 编号,姓名,convert(char(20),日期,110) 日期,时间1+ ' '+时间2 from temp0616