MYSQL:为每条记录创建不同列值的列表

时间:2014-01-28 20:17:31

标签: mysql string-concatenation distinct-values

Ticket_Number    Entered_By    Responded_By    Closed_By    Touched_by
----------------------------------------------------------------------
10001            John          NULL            Mike         John, Mike
10002            Sally         Mike            Mike         Sally, Mike
10003            NULL          George          Amber        George, Amber
10004            John          Holly           Timothy      John, Holly, Timothy

我的数据如上所示。我要做的是添加最后一列,Touched_By。基本上我知道我需要连接,删除重复项,然后构建一个没有重复分隔符的列表。我只是不知道如何。

2 个答案:

答案 0 :(得分:1)

你可以尝试一下吗?你可以在这里测试http://www.sqlfiddle.com/#!2/7a4d2/1

SELECT number, GROUP_CONCAT(by_whom)
FROM (
    SELECT number, entered_by AS by_whom FROM ticket
    UNION
    SELECT number, responsed_by AS by_whom FROM ticket
    UNION
    SELECT number, closed_by AS by_whom FROM ticket
) x
WHERE by_whom IS NOT NULL
GROUP BY number;

+--------+-----------------------+
| number | GROUP_CONCAT(by_whom) |
+--------+-----------------------+
|  10001 | Mike,John             |
|  10002 | Mike,Sally            |
|  10003 | Amber,George          |
|  10004 | John,Timothy,Holly    |
+--------+-----------------------+

请注意,GROUP_CONCAT()返回值的最大长度为mysql> SHOW VARIABLES LIKE 'group_concat_max_len'; +----------------------+--------+ | Variable_name | Value | +----------------------+--------+ | group_concat_max_len | 102400 | +----------------------+--------+ 1 row in set (0.00 sec) 。您的默认值就足够了,即102400。

{{1}}

答案 1 :(得分:0)

函数concat_ws()具有跳过NULL个参数的好功能。这使它对此很有用:

select t.*,
       concat_ws(', ', Entered_By,
                 (case when Responded_By = Entered_By
                       then NULL else Responded_By
                  end),
                 (case when Closed_By = Entered_By or Closed_By = Responded_By
                       then NULL else Closed_By
                  end)
                ) as Resolved_By

Here是一个SQL小提琴。