mysql查询,将行分组并连接成一行

y0u0uwnf  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(407)

我在mysql中有一个包含记录的表:

我已经编写了sql查询:

SELECT COUNT(*) AS number_of_contacts, channel_id, direction
FROM cic_case_contacts
WHERE case_id = 328678
GROUP BY channel_id, direction

结果如下:

我想获得如下信息(基于以上数据):

我试图通过使用我的\u sql\u函数组\u concat通过sql查询来获得它,但它不起作用:

SELECT COUNT(*) AS number_of_contacts, channel_id, GROUP_CONCAT(direction SEPARATOR ', ') AS directions
FROM cic_case_contacts
WHERE case_id = 328678 AND id IN(149196, 149195, 149194, 149193, 149192) AND `office_id` = 10
GROUP BY channel_id
ORDER BY channel_id

我将非常感谢你的帮助。

oprakyz7

oprakyz71#

你可以用 ConcatMySQL ```
drop table if exists Demo;
CREATE TABLE Demo
(
ID INT AUTO_INCREMENT PRIMARY KEY,
channelid int,
Name VARCHAR(20)
);

INSERT INTO Demo(channelid, Name)VALUES
(1,'in'),(1,'out'),(1,'in'),(1,'out'),(2,'in'),(2,'out'),(1,'in'),(1,'out'),(1,'in'),(2,'out'),(2,'in'),(2,'out'),(2,'in'),(1,'in'),(1,'in');

查询

SELECT SQL_CALC_FOUND_ROWS
channelid,
group_concat ( concat(name,':',channelid) )
FROM Demo
group by channelid;

SELECT FOUND_ROWS();

看小提琴演奏的结果
n53p2ov0

n53p2ov02#

请根据您的要求查找以下工作代码:

select tb.channelid, group_concat
(
  concat(tb.name,':',tb.MyCol2Count)

) as v1
from
(Select tbl.channelid,tbl.name,(LENGTH(tbl.val) - LENGTH(REPLACE(tbl.val,",","")) + 1) AS MyCol2Count
from 
(SELECT channelid, group_concat
(
  concat(name,':',channelid)

) as val,name
FROM Demo
group by channelid,Name) as tbl) as tb group by tb.channelid

您可以查看以下屏幕截图:http://springinfosoft.com/code/groupby_code.png

xyhw6mcr

xyhw6mcr3#

你可以用 GROUP_CONCAT 在子查询上,如下所示:

SELECT channelid, GROUP_CONCAT(
    CONCAT(direction, ': ', c)
    ORDER BY direction
    SEPARATOR ', '
) AS summary
FROM (
    SELECT channelid, direction, COUNT(*) AS c
    FROM t
    GROUP BY channelid, direction
) x
GROUP BY channelid

或者简单地使用条件聚合:

SELECT channelid, CONCAT_WS(', ',
    CONCAT('in: ',  COUNT(CASE WHEN direction = 'in'  THEN 1 END)),
    CONCAT('out: ', COUNT(CASE WHEN direction = 'out' THEN 1 END))
) AS summary
FROM t
GROUP BY channelid

相关问题