34,838
社区成员




合并列值:
--> 数据库版本:
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:[TB]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TB]')
AND type in (N'U'))
DROP TABLE [TB]
GO
---->建表
create table [TB]([name] varchar(4),[status] varchar(8))
insert [TB]
select '小张','普通员工' union all
select '小张','组长' union all
select '小二','经理' union all
select '小三','老板' union all
select '小三','员工'
GO
方法一:
SELECT a.name,
status =stuff((
select ','+convert(varchar(20),status) FROM [TB] WHERE name = a.name for xml path(''))
,1,1,'')
FROM [TB] a
group by a.name
方法二:
SELECT a.name,
status =STUFF(REPLACE(REPLACE(
(select status
FROM [TB]
where name = a.name
FOR XML AUTO
), '<TB status="', ','), '"/>', ''), 1, 1, '')
FROM [TB] a
group by a.name
--> 查询结果
SELECT * FROM [TB]
--> 删除表格
--DROP TABLE [TB]
-------------------------------------------
SQL SERVER 2000用函数处理
---->建表
create table [TB](date1 varchar(10),time1 varchar(5))
insert [TB]
select '2010-10-20','12:00' union all
select '2010-10-20','13:00' union all
select '2010-10-21','14:00' union all
select '2010-10-21','15:00' union all
select '2010-10-20','16:00'
GO
CREATE function dbo.fn_date(@date1 as varchar(50))
returns varchar(1000)
as
begin
declare @s varchar(1000)
set @s=''
select @s=@s+isnull(time1,'')+';'
from A where date1=@date1
return (@s)
end
select date1,dbo.fn_date(date1) as time1
from A
group by date1
----------------
2010-10-20 12:00;13:00;16:00;
2010-10-21 14:00;15:00