在嵌套选择中组合多个行

时间:2016-07-26 17:07:23

标签: sql sql-server

我有以下(结构不合理)表:

tbl.quotes A
quoteid | assignedID | created_by | name
int, int, varchar, varchar

tbl.quote_notes B
id | quoteID | userID | noteText
int, int, varchar, text

tbl.admins C
id | name
int, varchar

tbl.agents D
id | name
int, varchar

我有以下查询,但我需要在每个结果上为每个引号组合多个行以引用。

SELECT 
    A.quoteid,
    A.name,
    C.name,
    D.name,
    (SELECT 
        TOP 1 notetext
     FROM quote_notes B
     WHERE B.quoteid = A.quoteid
     ORDER BY dateentered DESC
    ) AS [notes]
    FROM quotes A
    LEFT JOIN admins C
        ON A.assignedid = C.id
    LEFT JOIN agents D
        ON A.created_by = D.id
WHERE A.createuserid = 'agentname'

这会产生并且不会将quote_notes.noteText组合成多行:

12345 | Quote Name | Admin Name | Agent Name | Notes

期望的结果:

12345 | Quote Name | Admin Name | Agent Name | Note1, Note2, Note3

我编写了一个while循环来组合行,但由于它使用变量,因此无法在嵌套的select语句中使用它。它也只适用于1 quoteid

DECLARE @rowcount INTEGER
DECLARE @Count INTEGER
DECLARE @note VARCHAR(MAX)
SET @Count = 1
SET @note = ''
SET @rowcount = (SELECT COUNT(quoteID) FROM quote_notes WHERE quoteID = '12345')

WHILE @Count<=@rowcount
    BEGIN
    IF @note!=''
        SET @note = @note+',' + (SELECT convert(varchar(max), noteText) FROM quote_notes WHERE id = @Count)
    ELSE
        SET @note = (SELECT noteText FROM quote_notes WHERE id = @Count)
    SET @Count=@Count+1
    END
SELECT @note AS note

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:3)

用于XML路径..

SELECT 
    A.quoteid,
    A.name,
    C.name,
    D.name,
        STUFF((SELECT 
        ',' +notetext
     FROM quote_notes B
     WHERE B.quoteid = A.quoteid
     for xml path('')
     ),1,1,'')
     AS [notes]
    FROM quotes A
    LEFT JOIN admins C
        ON A.assignedid = C.id
    LEFT JOIN agents D
        ON A.created_by = D.id
WHERE A.createuserid = 'agentname'