将记录从2“一对多”转换为一个记录

时间:2013-12-31 19:12:32

标签: tsql user-defined-functions

基本上,我想获得一个与此类似的记录集:

CustomerID, CustomerName, OrderNumbers
1           John Smith    112, 113, 114, 115
2           James Smith   116, 117, 118

目前我正在使用Sql Server UDF连接订单#s。

是否有更有效的解决方案?

1 个答案:

答案 0 :(得分:0)

1)There are allot of solutions

2)示例(SQL2005 +):

DECLARE @Customer TABLE (
    CustomerID INT PRIMARY KEY,
    Name NVARCHAR(50) NOT NULL
);
INSERT @Customer VALUES (1, 'Microsoft');
INSERT @Customer VALUES (2, 'Macrosoft');
INSERT @Customer VALUES (3, 'Appl3');

DECLARE @Order TABLE (
    OrderID INT PRIMARY KEY,
    CustomerID INT NOT NULL -- FK
);
INSERT @Order VALUES (1, 1);
INSERT @Order VALUES (2, 2);
INSERT @Order VALUES (3, 2);
INSERT @Order VALUES (4, 1);
INSERT @Order VALUES (5, 2);

SELECT  c.CustomerID, c.Name, oa.OrderNumbers
FROM    @Customer AS c
/*CROSS or */OUTER APPLY (
    SELECT STUFF((
        SELECT ',' + CONVERT(VARCHAR(11), o.OrderID) FROM @Order AS o
        WHERE o.CustomerID = c.CustomerID
        -- ORDER BY o.OrderID -- Uncomment of order nums must be sorted
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)'), 1, 1, '') AS OrderNumbers
) oa;

输出:

CustomerID  Name      OrderNumbers
----------- --------- ------------
1           Microsoft 1,4
2           Macrosoft 2,3,5
3           Appl3     NULL