1

我有以下问题,我无法成功完成。您的帮助将不胜感激。我正在使用 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

谢谢拉胡尔耆那教


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

我正在使用如下查询:

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

4 回答 4

3

这是一篇描述执行此操作的方法的文章:

将多行转换为 CSV 字符串

于 2008-12-27T15:28:14.373 回答
2

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

sql 2005 中的 PIVOT

sql 2005 中的 PIVOT

从上述答案的示例中,这是为您的表修改的 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)
于 2008-12-27T16:25:42.697 回答
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中为聚合字符串连接提供了一些专门的解决方案。该查询为自己尖叫。

于 2008-12-28T21:06:47.077 回答
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   
于 2016-06-14T22:57:55.517 回答