【问题标题】:SQL concat IDs of rows after group bySQL concat IDs of rows after group by
【发布时间】:2022-12-01 20:29:07
【问题描述】:

I'm trying to output a query that has a count of a group by but also, specifies the list of IDs in that row.

This is what I have so far:

SELECT
    title,
    period,
    COUNT(*)
FROM
    table
GROUP BY
    title, period

Example database

Title Period ID
Title2 MONTH 321
Title1 DAY 789
Title1 DAY 123
Title1 MONTH 123

Output

Title Period COUNT(*)
Title2 MONTH 1
Title1 DAY 2
Title1 MONTH 1

But I would like the output to be something like:

Title Period COUNT(*) Who?
Title2 MONTH 1 321
Title1 DAY 2 123, 789
Title1 MONTH 1 123

What do I need to add to my query to get this output? I've tried to use an SELF JOIN and a SELECT JOIN, but I cannot quite get the syntax right.

【问题讨论】:

  • So you are looking for an aggregate string concatenation function, like STRING_AGGR in SQLServer or LIST in Firebird, but then for MySQL.
  • I'm not familiar with those other languages/syntaxes, but that does sound right.

标签: mysql sql relational-database


【解决方案1】:

We can use GROUP_CONCAT:

SELECT
    title,
    period,
    COUNT(*),
    GROUP_CONCAT(id ORDER BY id separator ', ') AS Who
FROM
    yourtable
GROUP BY
    title, period
ORDER BY title DESC;

Note: I don't know if the two ORDER BY clauses are necessary for you. I just added them to produce exactly your outcome. Remove them if not needed.

You can also remove the "separator ', ') part if you don't require spaces after the comma.

Try out: db<>fiddle

Here the documentation: documentation

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 2022-09-22
  • 2023-04-03
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
相关资源
最近更新 更多