mysql-GROUP_CONCAT行转换为字符串

时间:2019-06-19 05:29:10

标签: mysql sql group-by group-concat

我有以下结果集:

req_id |  p_id  | ai_result  |  hash | sku
1      |  4     | Match      |  XAN  | HOW
1      |  4     | Match      |  HXN  | HOW
1      |  4     | Non Match  |  123  | HOW

我需要以下输出

sku  | matched  |  non_matched
HOW  | XAN, HXN |  123

据我所知:

SELECT sku, GROUP_CONCAT(hash) AS hash
FROM `sku_match` 
GROUP BY req_id, p_id

如何区分基于ai_result列的行并将它们分开放置。 像GROUP_CONCAT(hash) AS matched, GROUP_CONCAT(hash) AS non_matched一样?

1 个答案:

答案 0 :(得分:5)

尝试使用条件聚合:

SELECT
    sku,
    GROUP_CONCAT(CASE WHEN ai_result = 'Match' THEN hash END) AS matched,
    GROUP_CONCAT(CASE WHEN ai_result = 'Non Match' THEN hash END) AS non_matched
FROM sku_match
GROUP BY
    sku;

enter image description here

Demo