帮助递归查询

时间:2008-12-27 15:09:29

标签: sql sql-server common-table-expression recursive-query

我遇到了问题,我无法成功完成。我们将不胜感激。我正在使用SQL 2005,并尝试使用CTE。

表格包含以下2列

DocNum    DocEntry
1              234
2              324
2              746
3              876
3              764
4              100
4              387

预期结果如下

1                 234
2                 324, 746
3                 876, 764
4                 100, 387

由于 Rahul Jain


评论中转录的进一步解释:

我正在使用如下查询:

WITH ABC (DocNum, DocEntry) AS
   (SELECT DocNum, Cast(DocEntry As VARCHAR(8000))
        FROM Temp5
        WHERE DocNum = 1
    UNION ALL
    SELECT a.DocNum, A.DocEntry + ', ' + B.DocEntry
        FROM ABC B INNER JOIN Temp5 A ON B.DocNum +1= A.DocNum
         WHERE A.DOCNUM > 1)
SELECT * FROM ABC;

以上查询的结果如下

1 234
2 234, 324
2 234, 746
3 234, 746, 876
3 234, 746, 764

我不希望这些数字重复,如图所示。

4 个答案:

答案 0 :(得分:3)

这篇文章介绍了执行此操作的方法:

Converting Multiple Rows into a CSV String

答案 1 :(得分:2)

我不认为CTE是您问题的完整答案。你所追求的是一个PIVOT查询,其中PIVOT中的列数在查询时是未知的。这个问题和答案看起来像你所追求的:

PIVOT in sql 2005

PIVOT in sql 2005

从上面答案的示例中,这是为您的表修改的SQL(我将其命名为'q395075' - 所以您只需要用您的表名替换):

DECLARE @sql AS varchar(max)
DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique
DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique

SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']'
        ,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [col_' + CONVERT(varchar, PIVOT_CODE) + ']'
FROM (
    SELECT DISTINCT PIVOT_CODE
    FROM (
        SELECT DocNum, DocEntry, ROW_NUMBER() OVER (PARTITION BY DocNum ORDER BY DocEntry) AS PIVOT_CODE
        FROM q395075
    ) AS rows
) AS PIVOT_CODES

SET @sql = '
;WITH p AS (
    SELECT DocNum, DocEntry, ROW_NUMBER() OVER (PARTITION BY DocNum ORDER BY DocEntry) AS PIVOT_CODE
    FROM q395075
)
SELECT DocNum, ' + @select_list + '
FROM p
PIVOT (
    MIN(DocEntry)
    FOR PIVOT_CODE IN (
        ' + @pivot_list + '
    )
) AS pvt
'

PRINT @sql

EXEC (@sql)

答案 2 :(得分:1)

SELECT 
    DocNum,
    STUFF((SELECT ', ' + CAST(DocEntry AS VARCHAR(MAX)) AS [text()]
        FROM Temp5 b
        WHERE a.DocNum = b.DocNum
        FOR XML PATH('')), 1, 2, '') AS DocEntry
FROM Temp5 a
GROUP BY DocNum

Itzik Ben-Gan在他出色的着作T-SQL QUERYING中有一些专门用于聚合字符串连接的解决方案。查询为自己尖叫。

答案 3 :(得分:0)

create table #a(DocNum int,  DocEntry int)

insert into #a
select 1,234 union all
select 2,324 union all
select 2,746 union all
select 3,876 union all
select 3,764 union all
select 4,100 union all
select 4,387 


select
    DocNum,
    stuff((
        select ',' + convert(varchar(25),t.DocEntry)
        from #a t
        where t.DocNum = t1.DocNum
        order by t.DocEntry
        for xml path('')
    ),1,1,'') as name_csv
from #a t1
group by DocNum
; 

输出

DocNum name_sv

   1    234    
   2    324,746    
   3    764,876    
   4    100,387