我有一个表tblEmpBatch
Username Filename BatchId
a f1 1
b f2 1
c f3 2
d f4 2
我想输出
Username Filename BatchId
a,b f1,f2 1
c,d f3,f4 2
如何为此编写SQL查询。
答案 0 :(得分:0)
试试这个......
SELECT
GROUP_CONCAT(Username) AS Username,
GROUP_CONCAT(Filename) AS Filename,
FROM tbl
GROUP BY BatchId
答案 1 :(得分:0)
declare @t table (username varchar(1),Filemname varchar(10),Batchid int)
insert into @t (username,Filemname,Batchid)values ('a','f1',1)
insert into @t (username,Filemname,Batchid)values ('b','f2',1)
insert into @t (username,Filemname,Batchid)values ('c','f3',2)
insert into @t (username,Filemname,Batchid)values ('d','f4',2)
select distinct t.[Batchid],
STUFF((SELECT distinct ', ' + t1.username
from @t t1
where t.[Batchid] = t1.[Batchid]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'') username,
STUFF((SELECT distinct ', ' + t1.Filemname
from @t t1
where t.[Batchid] = t1.[Batchid]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'') Filemname
from @t t;
答案 2 :(得分:0)
试试这个:(要在表中使用它,根据需要更改表名并检查列名)
CREATE TABLE #TABLE2(Username varchar(10), filename VARCHAR(10), batchid INT)
INSERT INTO #TABLE2 VALUES('a' , 'f1' , 1)
INSERT INTO #TABLE2 VALUES('b' , 'f2' , 1)
INSERT INTO #TABLE2 VALUES('c' , 'f3' , 2)
INSERT INTO #TABLE2 VALUES('d' , 'f4' , 2)
select
Username =
stuff((
select
', ' + t2.Username
from #table2 t2
where
t2.batchid = t1.batchid
group by t2.Username
for xml path(''), type).value('.', 'varchar(max)'
), 1, 2, ''),
filename =
stuff((
select
', ' + t2.filename
from #table2 t2
where
t2.batchid = t1.batchid
group by t2.filename
for xml path(''), type).value('.', 'varchar(max)'
), 1, 2, ''), batchid
from #table2 t1 group by batchid
答案 3 :(得分:0)
试试这个工作正常
Select distinct ST2.BatchId as BatchID, (
Select ST1.Filename + ',' AS[text()]
From tblEmpBatch ST1
Where ST1.BatchId= ST2.BatchId
ORDER BY ST1.BatchId
For XML PATH ('')
)[FileName]
,
(
Select ST1.Username + ',' AS [text()]
From tblEmpBatch ST1
Where ST1.BatchId= ST2.BatchId
ORDER BY ST1.BatchId
For XML PATH ('')
)[UserName]
From dbo.tblEmpBatch ST2