【问题标题】:MySQL: Group and flatten elements on a columnMySQL:对列上的元素进行分组和展平
【发布时间】:2014-02-19 14:05:18
【问题描述】:

如果我有意见:

Movie             Genre    Actor
-------------------------------------------
Ocean's Twelve    Crime    George Clooney
Ocean's Twelve    Crime    Julia Roberts
Ocean's Twelve    Crime    Brad Pitt
Forrest Gump      Drama    Tom Hanks

我如何按电影标题分组,但像这样展平其他列:

Movie             Genre    Actor
-------------------------------------------
Ocean's Twelve    Crime    George Clooney, Julia Roberts, Brad Pitt
Forrest Gump      Drama    Tom Hanks

注意,如果一个元素是等价的,它就不会重复(例如Crime

【问题讨论】:

    标签: mysql sql select group-by group-concat


    【解决方案1】:

    MySQL

    使用GROUP_CONCAT()函数:

    SELECT movie, Genre, GROUP_CONCAT(Actor) AS Actor
    FROM tableA
    GROUP BY movie, Genre
    

    SQL 服务器

    SELECT A.movie, A.Genre, MAX(STUFF(B.ActorNames, 1, 1, '')) AS Actor
    FROM tableA A 
    CROSS APPLY(SELECT ' ' + Actor + ',' FROM tableA B 
                WHERE A.movie = B.movie AND A.Genre = B.Genre 
                FOR XML PATH('')
              ) AS B (ActorNames)
    GROUP BY A.movie, A.Genre
    

    【讨论】:

      【解决方案2】:

      您正在寻找GROUP_CONCAT

      select Movie, Genre, group_concat(Actor separator ', ') as `Actors`
      from
      movies
      group by Movie, Genre;
      

      【讨论】:

      • 如何在 sql server 中做到这一点?
      • @mhasan 使用其中一种解决方法herehere。我通常使用XML PATH hack。
      【解决方案3】:

      你需要 group_concat 和 group by http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat 试试这个

      select Movie, Genre, group_concat(Actor) from view_name group by Movie
      

      【讨论】:

        猜你喜欢
        • 2018-08-26
        • 1970-01-01
        • 2019-11-25
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多