【问题标题】:Multiple Row to Single Row in a single Table [closed]单个表中的多行到单行[关闭]
【发布时间】:2020-07-15 22:12:08
【问题描述】:

我需要一个 Sql 来从多行中获取单行中的数据。 仅供参考,我使用的是 Microsoft sql server。

示例:

StudentId|StudentName|CourseName
1        |X          |CSE-1201
3        |Y          |CSE-1201
1        |X          |EEE-1201

输出如下:

StudentId|StudentName|CourseName
1        |X          |CSE-1201, EEE-1201
3        |Y          |CSE-1201

我尝试使用 group by。但它得到聚合函数相关的错误。我可以理解为什么它会出错。但我无法解决这个问题。我得到了与加入表相关的不同类型的解决方案。比如 T-SQL、Stuff、Join 等。

但我无法理解,他们实际上在做什么。我想了解我给定的场景。

【问题讨论】:

  • MySQL 或 (MS)sql-server
  • 它的 (MS) sql-server。我不能在这里添加这个标签

标签: sql sql-server tsql sql-server-2008 group-by


【解决方案1】:

由于您标记 SQL Server 2008

WITH CTE AS
(
  SELECT *
  FROM
  (
    VALUES
    (1, 'X', 'CSE-1201'),
    (3, 'Y', 'CSE-1201'),
    (1, 'X', 'EEE-1201')
  ) T(StudentId, StudentName, CourseName)
)
SELECT StudentId, 
       StudentName,
       STUFF(
             (
               SELECT ',' + CourseName 
               FROM CTE T 
               WHERE StudentId = TT.StudentId
               FOR XML PATH('')
             )
            , 1, 1,'') Result
FROM CTE TT
GROUP BY StudentId, StudentName;

但请记住,您应该立即升级。 End support SQL Server 2008

【讨论】:

    【解决方案2】:

    对于MySql试试,

        SELECT StudentId, StudentName, dbo.GROUP_CONCAT(CourseName) 
              FROM TableName 
              GROUP BY StudentId, StudentName
    

    对于 SQL Server 试试,

    select StudentId, StudentName, stuff((select '; ' + a.CourseName
              from TableName a
               Group By StudentId, StudentName
              for xml path ('')
             ), 1, 2, '')  as CourseNames
    

    【讨论】:

    • 非常感谢。我试过你的第二个代码。但它得到错误'无效的列名'StudentId'。我有名为“StudentId”的字段。但它显示这种类型错误
    • 可能是因为我们在上面的查询中定义了一个别名,所以要么删除别名,要么将列名写为 a.StudentId 、 a.StudentName 等(你也必须将“TableName”替换为表的名称。)
    【解决方案3】:

    你不能字符串聚合。

    在 MySQL 中,使用 group_concat():

    select
        studentId,
        studentName, 
        group_concat(courseName order by courseName separator ', ') courseNames
    from mytable
    group by studentId, studentName
    

    在 SQL Server 2017 或更高版本中,使用string_agg()

    select
        studentId,
        studentName, 
        string_agg(courseName, ', ') within group(order by courseName) courseNames
    from mytable
    group by studentId, studentName
    

    【讨论】:

    • 非常感谢。但我使用的是 Microsoft SQL Server 2012。它返回“没有名为 group_concat 的内置函数”
    猜你喜欢
    • 1970-01-01
    • 2014-01-27
    • 2010-11-15
    • 2013-03-11
    • 2022-10-04
    • 1970-01-01
    • 2020-01-25
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多