[英]Rolling up multiple rows into a single row and column for SQL Server data
[英]Rolling Multiple Rows into a Single Row Based on Matching Data in SQL Server
我在 SQL 服务器中有一个表格,其中包含以下布局和一些示例数据:
| ReferenceNumber | TagID |
+-----------------+-------+
| 114942 | 1 |
| 114942 | 2 |
| 114942 | 3 |
| 114942 | 4 |
| 123456 | 10 |
是否可以将 ReferenceNumber 行合并为一行,所以:
| ReferenceNumber | TagID |
+-----------------+---------+
| 114942 | 1,2,3,4 |
| 123456 | 10 |
我试过了:
select
ReferenceNumber,
stuff((select '; ' + TagID from RefTagTable
for xml path('')), 1, 1,'')[Tags]
from
RefTagTable
order by
ReferenceNumber
输出:
| ReferenceNumber | Tags |
+-----------------+------------+
| 114942 | 1,2,3,4,10 |
| 123456 | 1,2,3,4,10 |
任何帮助将不胜感激。 谢谢
假设这是针对少量(ish)数据,您可以关联子查询。 它嵌套(因此可以将查询视为在外部查询中每行运行一次。优化器通常优化得比这更好,但在某种程度上取决于它是否比其他方法更适合您。
DROP TABLE #tags
GO
CREATE TABLE #tags (ReferenceNumber varchar(10), TagId varchar(20))
GO
INSERT INTO #tags (ReferenceNumber , TagId )
SELECT 114942, 1
UNION SELECT 114942, 2
UNION SELECT 114942, 3
UNION SELECT 114942, 4
UNION SELECT 123456, 1
GO
SELECT ReferenceNumber,
stuff((select '; ' + TagID from #Tags AS CorrTagTable WHERE CorrTagTable.ReferenceNumber = Reftagtable.ReferenceNumber
for xml path('')), 1, 1,'')[Tags]
from #tags AS RefTagTable
order by ReferenceNumber
GO
生产:
ReferenceNumber Tags
114942 1; 2; 3; 4
114942 1; 2; 3; 4
114942 1; 2; 3; 4
114942 1; 2; 3; 4
123456 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.