多行合并到一行内
SQL2000,列1,列2是组合主键
列1 列2
1 a
1 b
1 c
2 aa
2 bb
2 c
3 a
....
想要结果:
1 a,b,c
2 aa,bb,c
3 a
...
看论坛里语句,报错:xml 附近有语法错误
select 列1,
aaa= stuff((select ' '+列2 from t1 where s.列1=列1 for xml path('')),1,1,'')
from t1 s
group by 列1
应该怎么实现?谢谢!
[解决办法]
/*
工单号 操作者
a1 张三
a1 王二
a1 李四
现在要得到查询结果:
工单号 操作者
a1 张三、王二、李四
*/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[test1]') AND type in (N'U'))
DROP TABLE [dbo].[test1]
GO
CREATE TABLE [dbo].[test1](
工单号 [varchar](10) NOT NULL,
操作者 [varchar](10) NOT NULL
) ON [PRIMARY]
GO
INSERT [test1]
VALUES ('a1','张三'),('a1','王二'),('a1','李四')
select 工单号,
操作者=stuff((select '、'+操作者
from test1
where 工单号=t.工单号
for xml path('')),1,1,'')
from test1 t
group by 工单号
DECLARE @s VARCHAR(4000)
SELECT @s=@s +'、'+操作者 from test1 WHERE 工单号='a1'
PRINT @s
SET @s=STUFF(@s,1,1,'')
EXEC('select 工单号,'+@s+' FROM test1')
--#1.sql2000中只能用自定义的函数,参考如下
IF OBJECT_ID('dbo.fn_merger', 'FN') IS NOT NULL
DROP FUNCTION dbo.fn_merger
GO
CREATE FUNCTION fn_merger(@id INT)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @rv NVARCHAR(MAX)
SET @rv = N''
SELECT @rv = @rv + ',' + [name] FROM dbo.temp WHERE id = @id
RETURN STUFF(@rv,1,1,'')
END
GO
--TEST:
SELECT
id,
[name] = dbo.fn_merger(id)
FROM temp
GROUP BY id
create function dbo.f_str(@id int) returns varchar(100)
as
begin
declare @str varchar(1000)
set @str = ''
select @str = @str + ',' + cast(value as varchar) from tb where id = @id
set @str = right(@str , len(@str) - 1)
return @str
end
go
--调用函数
select id , value = dbo.f_str(id) from tb group by id