mysql - GROUP_CONCAT 行变成一个字符串

mysql - GROUP_CONCAT rows into a string

我有以下结果集:

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?

尝试使用条件聚合:

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;

Demo