I have a table that tells me the products as well as which state they’re sold in.
x
PRODUCT | STATE
-------------------------------------------------
yPhone | Alabama
yPad | Massachusetts
yPhone | Alaska
yPhone | Wyoming
yPad | Alabama
yPhone | California
yPad | Florida
What I would like is to extract from the database is a list of every state each product is sold in as well as the count of states, grouped by the product; i.e.
PRODUCT | STATE | COUNT(STATE)
---------------------------------------------------------------
yPhone | Alabama, Alaska, Wyoming, California | 4
yPad | Massachusetts, Alabama, Florida | 3
Is there a way to do this in a single SELECT statement, or multiple SELECT statements?
Advertisement
Answer
I found the answer, the GROUP_CONCAT
function can be used to get a list that’s concatenated.
https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat