Merge rows with same id but different values into single row per id
Solution 1:
The columns of an SQL query must be fixed at the time the query is parsed. A query cannot append more columns as it discovers the data during execution.
You could use pivot-table techniques, but only if you know how many columns you need for the number of categories per product.
I suggest you fetch the results in rows as in your first example, and then write code in your client application to format it into columns.