基于字段值的行到列

时间:2019-07-09 03:43:12

标签: mysql

我有两个表docspeople

  • docs表包含:iddoc_id
  • people表包含:iddoc_idtypefirstnamelastname

我想要基于group_concat进行people.type,并在其自己的列中包含type

TABLE模式和数据:

CREATE TABLE IF NOT EXISTS `people` (
    `id` int(6) unsigned NOT NULL,
    `doc_id` varchar(6) NOT NULL,
    `type` varchar(6) NOT NULL,
    `firstname` varchar(25) NOT NULL,
    `lastname` varchar(25) NOT NULL
      ) DEFAULT CHARSET=utf8;

INSERT INTO people (`id`, `doc_id`,`type`,`firstname`,`lastname`) VALUES
('1','ABC001','From','John','Smith'),
('2','ABC001','To','Jonas','Doot'),
('3','ABC001','To','John','Howard'),
('4','ABC002','From','Holland','Jones'),
('5','ABC002','To','Tim','Jones'),
('6','ABC002','To','Julia','Smith');

CREATE TABLE IF NOT EXISTS `docs` (
    `id` int(6) unsigned NOT NULL,
    `doc_id` varchar(6) NOT NULL
      ) DEFAULT CHARSET=utf8;

INSERT INTO docs (`id`,`doc_id`) VALUES 
('1', 'ABC001'),
('2', 'ABC002');

这是我目前拥有的东西,它可以工作,但是同一doc_id仍然有“重复”行,我需要的是将具有相同doc_id的行“合并”为一个。 / p>

SELECT d.doc_id, 
       p.type, 
       CASE p.type WHEN 'From' 
            THEN GROUP_CONCAT(CASE WHEN p.type = 'From' 
                 THEN CONCAT(p.firstname,' ',p.lastname) END SEPARATOR '; ') END 'From', 
       CASE p.type WHEN 'To' 
            THEN GROUP_CONCAT(CASE WHEN p.type = 'To' 
                 THEN CONCAT(p.firstname,' ',p.lastname) END SEPARATOR '; ') END 'To' 
            FROM docs d 
      INNER JOIN people p ON d.doc_id = p.doc_id 
GROUP BY d.doc_id, p.type

我当前的输出是: Current Output

我正在寻找的是:

doc_id       From             To
ABC001       John Smith       John Howard; Jonas Doot
ABC002       Holland Jones    Tim Jones; Julia Smith

SQL提琴: http://sqlfiddle.com/#!9/096f891/4

2 个答案:

答案 0 :(得分:2)

p.type中取出GROUP BY,这样就不必将每种类型都放在自己的行中。

此外,CASE表达式应位于GROUP_CONCAT内。聚集函数应该在分组查询中位于顶层。

SELECT 
    d.doc_id, 
    GROUP_CONCAT(
        CASE p.type WHEN 'From' 
            THEN CONCAT(p.firstname,' ',p.lastname) 
        END
        SEPARATOR '; '
   ) 'From', 
   GROUP_CONCAT(
        CASE p.type WHEN 'To' 
            THEN CONCAT(p.firstname,' ',p.lastname) 
        END 
        SEPARATOR '; ') 'To' 
FROM docs d 
INNER JOIN people p ON d.doc_id = p.doc_id 
GROUP BY d.doc_id

答案 1 :(得分:0)

您可以使用此sql enter image description here

select U.doc_id,
    GROUP_CONCAT( U.`From` SEPARATOR '; ' ) 'From',
  GROUP_CONCAT( U.to SEPARATOR '; ' ) 'To' 
    from (
    SELECT
    d.doc_id,
    p.type,
    ( CASE p.type WHEN 'From' THEN GROUP_CONCAT( concat( p.firstname, ' ', p.lastname ) SEPARATOR '; ' ) END ) 'From',
  ( CASE p.type WHEN 'To' THEN GROUP_CONCAT( concat( p.firstname, ' ', p.lastname ) SEPARATOR '; ' ) END ) 'To' 
FROM
    docs d  INNER JOIN people p ON d.doc_id = p.doc_id 
GROUP BY
    d.doc_id,
    p.type)
    U GROUP BY U.doc_id