【问题标题】:SQL - combine multiple rows in to a single as a listSQL - 将多行合并为一个列表
【发布时间】:2017-11-28 11:53:22
【问题描述】:

如何在 SQL 中将多行组合/合并为单行作为列表。

[原场景:]

[需要的场景:]

【问题讨论】:

标签: sql merge


【解决方案1】:

SQL Server 提供ROW_NUMBER() 函数来实现上述功能

SELECT CASE WHEN ROW_NUMBER() OVER(PARTITION BY [column1] ORDER BY [column1]) > 1
            THEN ''
            ELSE CAST([column1] AS VARCHAR)
        END [column1],
        [column2]
FROM <table>;

编辑:使用STUFF()函数

select 
       [column1],
       [column2] = stuff(
                          (select DISTINCT ' '+[column2] from <table> where [column1] = t.[column1] for xml path('')),
                          1,1, ''
                    )
        from <table> t group by [column1]

结果:

column1 column2
1       Value 1 Value 2 Value 3
2       Value 4
3       Value 5 Value 6

【讨论】:

  • 这为 column1 中的每个值在 column2 中提供了单独的行,但我希望 column2 中的单个行用于 column1 中的每个值。
【解决方案2】:

感谢@Yogesh 的帮助!!

我使用了以下查询,它对我来说工作正常,并按要求显示数据required Scenario:

    Select distinct ST2.SubjectID, 
    substring(
        (
            Select CHAR(10) +ST1.StudentName  AS [text()]
            From dbo.Students ST1
            Where ST1.SubjectID = ST2.SubjectID
            ORDER BY ST1.SubjectID
            For XML PATH ('')
        ), 2, 1000) [Students]
From dbo.Students ST2

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2016-03-07
    • 1970-01-01
    • 2012-05-27
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多