在SQL Server查询中将一列行转换为仅一列
我在SQL Server 2012中有此查询:在SQL Server查询中将一列行转换为仅一列,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,我在SQL Server 2012中有此查询: select tblplantitle.id, tblplantoproductpayment.productid from tblplantitle inner join tblplan on tblplan.plantitleid = tblplantitle.id inner join tblplantoproductpayment on tblplantoproductpayment.planid
select
tblplantitle.id, tblplantoproductpayment.productid
from
tblplantitle
inner join
tblplan on tblplan.plantitleid = tblplantitle.id
inner join
tblplantoproductpayment on tblplantoproductpayment.planid = tblplan.id
group by
tblplantitle.id, tblplantoproductpayment.productid
结果如下:
id productid
1 1
1 2
1 3
1 10
2 5
2 1
3 4
3 11
但我想要这个结果:
1 1,2,3,10
2 5,1
3 4,11
我怎样才能得到这个结果?试试这个:
WITH cte as
(
select
tblplantitle.id, tblplantoproductpayment.productid
from
tblplantitle
inner join
tblplan on tblplan.plantitleid = tblplantitle.id
inner join
tblplantoproductpayment on tblplantoproductpayment.planid = tblplan.id
group by
tblplantitle.id, tblplantoproductpayment.productid
)
SELECT id, productid =
STUFF((SELECT ', ' + productid
FROM cte b
WHERE b.id= a.id
FOR XML PATH('')), 1, 2, '')
FROM cte a
GROUP BY id
使用下面的查询获得所需的输出
SELECT tblplantitle.id
, STUFF((SELECT ', ' + CAST(tblplantoproductpayment.productid AS VARCHAR(10)) [text()]
FROM tblplantoproductpayment
WHERE tblplantoproductpayment.planid = tblplan.id
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,' ') List_ProductIds
FROM tblplantitle
INNER JOIN tblplan on tblplan.plantitleid = tblplantitle.id
GROUP BY tblplantitle.id
你听说过透视表吗?