I've seen many answers to group_concat one column/multiple rows into multiple columns, but I cannot find how you populate the new columns with data from a second column.
My table of data looks like this:
first_name doc_number doc_status
a 1 new
a 2 new
b 3 pending
b 4 approved
c 5 new
c 6 approved
c 7 approved
This is the result I would like:
first_name doc_status_new doc_status_pending doc_status_approved
a 1,2
b 3 4
c 5 6,7
This is the result I get:
first_name doc_status_new doc_status_pending doc_status_approved
a 1,2
b 3,4
c 5,6,7
Row 2 shouldn't have '3,4' in the same column. And Row 3 shouldn't have "5,6,7" in the same column either. I do not know how to get group_concat to only list the doc_number that is relevant to that 'where' statement only.
This is the code I've used:
select
first_name,
case when doc_status = 'new' then group_concat(doc_number) end as doc_status_new,
case when doc_status = 'pending' then group_concat(doc_number) end as doc_status_pending,
case when doc_status = 'approved' then group_concat(doc_number) end as doc_status_approved
from table_name
group by first_name;