【问题标题】:combining rows that contain two separate fields of the same value [duplicate]组合包含相同值的两个单独字段的行[重复]
【发布时间】:2017-06-02 04:05:04
【问题描述】:

我有一个格式如下的表格:

title            source              subject   
Bill hits Fred   newspaper 1/1/17    Bill     
Bill hits Fred   newspaper 1/1/17    Fred
Bill hits Fred   newspaper 1/1/17    Violence
Mary likes pie   newspaper 1/4/17    Mary
Mary likes pie   newspaper 1/4/17    Pie 
Mary likes pie   newspaper 1/4/17    Apple
John dies        newspaper 1/4/17    John 
John dies        newspaper 1/4/17    Obituary
...

我需要实现的是一个查询,该查询查找标题和源字段具有相同值的所有行,并组合成一条连接主题字段的记录。即上述数据的输出将是:

title            source              subject   
Bill hits Fred   newspaper 1/1/17    Bill, Fred, Violence     
Mary likes pie   newspaper 1/4/17    Mary, Pie, Apple
John dies        newspaper 1/4/17    John, Obituary
...

我认为我需要 GROUP_CONCAT,但不确定用于比较所有行的标题和来源的确切语法。类似于:

select title, source, GROUP_CONCAT(subject) from mytable
WHERE

???

解决方案:我缺少 GROUP BY:

SELECT title, source, GROUP_CONCAT(subject) from mytable GROUP BY title, source

【问题讨论】:

  • 你需要一个合适的GROUP BY

标签: mysql


【解决方案1】:

用途:

SELECT title, source, GROUP_CONCAT(subject) from mytable GROUP BY title, source

【讨论】:

  • 啊...GROUP BY,我觉得很傻。非常感谢
【解决方案2】:

试试这个

select title,source,group_concat(subject) as subject from tbl5 group by title;

check on fiddle

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多