T-SQL将多个记录连接到一个记录中

时间:2016-06-10 19:07:14

标签: sql-server tsql

我想将下表中的记录合并为每个PolNo,Year,Platform,Number的单个记录。

| PolNo | YEAR | Platform | Number | Record | memo                |
|-------|------|----------|--------|--------|---------------------|
| 123   | 2010 | pc       | 1      | 1      | The user had issues |
| 123   | 2010 | pc       | 1      | 2      | with the os.        |
| 123   | 2009 | pc       | 2      | 1      | Replaced RAM        |
| 123   | 2010 | mac      | 1      | 1      | Ordered new CDs     |
| 564   | 2009 | mac      | 1      | 1      | Broken CD TRAY      |
| 564   | 2010 | mac      | 1      | 1      | USB port dead       |
| 564   | 2010 | pc       | 1      | 1      | Ordered replacement |
| 564   | 2010 | pc       | 1      | 2      | laptop              |

记录将合并为一个记录(记录列不会结转)。同时,PolNo,Year,Platform和Number被连接成一个ID而不是单个列。

| ID  | YEAR | Platform | memo                             |
|-----|------|----------|----------------------------------|
| 123 | 2010 | pc-1     | The user had issues with the os. |
| 123 | 2009 | pc-2     | Replaced RAM                     |
| 123 | 2010 | mac-1    | Ordered new CDs                  |
| 564 | 2009 | mac-1    | Broken CD TRAY                   |
| 564 | 2010 | mac-1    | USB port dead                    |
| 564 | 2010 | pc-1     | Ordered replacement laptop       |

正如您所看到的,我将上面第1行和第6行中的记录加入到一个连续的备忘录字段中。然而,我有一些备忘录字段,有21或22个记录可以组合/加入。

不确定我将如何实现这一目标。

思考光标,但我没有太多经验,听说它无效。该表有大约64k行可以操作(其中22k有多个记录)

1 个答案:

答案 0 :(得分:2)

您可以使用旧的“FOR XML”技巧来聚合记录文本:

CREATE TABLE #Records
(
    PolNo SMALLINT
    , Year SMALLINT
    , Platform NVARCHAR(16)
    , Number TINYINT
    , Record TINYINT
    , Memo NVARCHAR(256)
);

INSERT INTO #Records(PolNo, Year, Platform, Number, Record, Memo)
VALUES
    (123, 2010, 'pc', 1, 1, 'The user had issues')
    ,(123, 2010, 'pc', 1, 2, 'with the os.')
    ,(123, 2009, 'pc', 2, 1, 'Replaced RAM')
    ,(123, 2010, 'mac', 1, 1, 'Ordered new CDs')
    ,(564, 2009, 'mac', 1, 1, 'Broken CD TRAY')
    ,(564, 2010, 'mac', 1, 1, 'USB port dead')
    ,(564, 2010, 'pc', 1, 1, 'Ordered replacement')
    ,(564, 2010, 'pc', 1, 2, 'laptop')

SELECT *
FROM #Records;

WITH RecordIdentifier AS
(
    SELECT PolNo, Year, Platform, Number
    FROM #Records
    GROUP BY PolNo, Year, Platform, Number
)

SELECT CONCAT(PolNo, '-', Year, '-', Platform, '-', Number) AS Id
    , (SELECT ' ' + Memo
            FROM #Records forAggregation
            WHERE forAggregation.PolNo = record.PolNo
                AND forAggregation.Year = record.Year
                AND forAggregation.Platform = record.Platform
                AND forAggregation.Number = record.Number
            ORDER BY forAggregation.Record
            FOR XML PATH ('')
            ) AS Memo
FROM RecordIdentifier record
ORDER BY Id

DROP TABLE #Records
相关问题