如何合并相同列
比如:
一表里有(Comments)
ID InfoId Title AddTimes
1 3 你好 2007-4-29
2 3 Hello 2007-4-30
3 14 China 2007-4-28
4 14 Englist 2007-4-30
合并列我现在只要显示出时间是最新的信息
2 3 Hello 2007-4-30
4 14 Englist 2007-4-30
执行结果就会是这样.
------解决方案--------------------如果没有规则:就用
--先取出符合条件的ID
declare @ID varchar(4000)
set @ID= ' '
declare @InfoId int
declare @AddTimes datetime
--定义游标
declare my_cursor cursor for
SELECT InfoId,max(AddTimes) as AddTimes FROM [temp] group by InfoId
open my_cursor
fetch next from my_cursor into @InfoId,@AddTimes
while @@fetch_status=0
begin
select @ID=@ID+convert(varchar,[id])+ ', ' from [temp] where InfoId=@InfoId and AddTimes=@AddTimes
fetch next from my_cursor into @InfoId,@AddTimes
end
close my_cursor
deallocate my_cursor
--去掉最后一个逗号
set @ID=left(@ID,len(@ID)-1)
declare @SQL varchar(4000)
set @SQL= 'select * from [temp] where [id] in ( '+@ID+ ') '
exec (@SQL)