Search code examples
mysqlsqlgroup-bygroup-concat

mysql - GROUP_CONCAT rows into a string


I have a following result set:

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

I need to have the following output

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

Here's as far as I could get:

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

How can I distinguish rows based on ai_result column and put them separately. Something like GROUP_CONCAT(hash) AS matched, GROUP_CONCAT(hash) AS non_matched?


Solution

  • Try using conditional aggregation:

    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