简体   繁体   English

SQL服务器中基于匹配数据将多行滚动为单行

[英]Rolling Multiple Rows into a Single Row Based on Matching Data in SQL Server

I have a table in SQL Server with the following layout and some sample data:我在 SQL 服务器中有一个表格,其中包含以下布局和一些示例数据:

| ReferenceNumber | TagID |
+-----------------+-------+
| 114942          |   1   |
| 114942          |   2   |
| 114942          |   3   |
| 114942          |   4   |
| 123456          |  10   |

Is it possible to consolidate like ReferenceNumber rows into a single row, so:是否可以将 ReferenceNumber 行合并为一行,所以:

| ReferenceNumber | TagID   |
+-----------------+---------+
| 114942          | 1,2,3,4 |
| 123456          | 10      |

I've tried:我试过了:

select 
    ReferenceNumber,
    stuff((select '; ' + TagID from RefTagTable
           for xml path('')), 1, 1,'')[Tags]
from 
    RefTagTable
order by 
    ReferenceNumber

which outputs:输出:

| ReferenceNumber | Tags       |
+-----------------+------------+
| 114942          | 1,2,3,4,10 |
| 123456          | 1,2,3,4,10 |

Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks谢谢

Assuming this is for small (ish) amount of data, you can correlate the subquery.假设这是针对少量(ish)数据,您可以关联子查询。 It nests (so the query can be thought of as running once per row in the outer query. The optimiser normally optimises better than that but depends a bit on volumes as to whether it works for you better than other approaches.它嵌套(因此可以将查询视为在外部查询中每行运行一次。优化器通常优化得比这更好,但在某种程度上取决于它是否比其他方法更适合您。

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 

Produces:生产:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM