[SOLVED] MySQL group records based on a column value

Issue

Here’s my table schema:

Table Schema for Test Table

In the above test table I want to group my records by user_by and message_type only when the message_type = "push_message".

I am trying to achieve it without any sub query, suggestions please.

I tried this

SELECT * FROM `test` group by (CASE WHEN message_type = 'push_message' THEN user_by ELSE id END);

But throws an error in MySQL.

Here’s what I want:
enter image description here

Solution

Thank you for your responses. After some more research I got it right.

SELECT id,
       user_id,
       user_by,
       message_type
FROM test
GROUP BY IF(message_type = 'push_message', concat(user_by, message_type), id);

Answered By – Jitender Yadav

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *