-1

我试图在 a.OrderNumber = b.OrderNumber 上返回一行结果,其中表 b 有多行服务注释。我是否需要将评论连接到一个字段结果中以防止出现多行,我该怎么做?这就是我所拥有的。

SELECT a.OrderNumber,
    b.Comment,
    b.Comment,
    b.DATE
FROM Orders a
LEFT JOIN Comments b ON a.OrderNumber = b.OrderNumber

我在找:

   OrderNumber            Comment
   1200         01-01-13 Repair made, 01-02-13 Billed Customer

我得到的是:

OrderNumber            Comment            Date
1200              Repair made        01-01-13
1200              Billed Customer    01-02-13

这是我目前的结果:

在此处输入图像描述

4

1 回答 1

0

由于 OP 似乎对提供的代码示例有困难,我已经更新了答案以包含完整的代码结果,看看问题现在如何包含足够的信息来近似底层架构。

顺便说一句,尽量不要使用保留字作为列名。

CREATE TABLE Orders (OrderNumber INT);
GO
CREATE TABLE Comments (OrderNumber INT, Comment VARCHAR(255), CommentDate DATETIME);
GO

INSERT INTO Orders VALUES (1),(2);
INSERT INTO Comments VALUES
    (1, 'Stuff', GETDATE()),
    (1, 'Other Stuff', GETDATE()),
    (2, 'More stuff', GETDATE())

;WITH cteOrderComment AS (
    SELECT a.OrderNumber
        ,STUFF((
            SELECT CONVERT(VARCHAR, C.CommentDate, 10) + ' ' + Comment + ', '
            FROM Comments C
            WHERE C.OrderNumber = A.OrderNumber
            FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR (MAX)')
        ,1,0,'') [Comments]
    FROM Orders a
    GROUP BY a.OrderNumber
)

SELECT T.OrderNumber, LEFT(T.Comments, LEN(T.Comments) - 1) [Comments]
FROM cteOrderComment T
GO

DROP TABLE Orders
DROP TABLE Comments
于 2013-11-05T17:21:54.497 回答