Skip to content
Advertisement

sql query for grouping column into row

So, I have table like this

Name        Slot
 A           1
 A           2
 A           3
 B           1
 B           2

and I want to make query so the result is like

Name    slot1    slot2    slot3    slot4
 A        Y        Y        Y       N
 B        Y        Y        N       N

or

A:1,2,3
B:1,2

I have try to use GROUP BY but I dont know how to get the slot number.

Please help, thank you!

Advertisement

Answer

With conditional aggregation:

select name,
  max(case when slot = 1 then 'Y' else 'N' end) slot1,
  max(case when slot = 2 then 'Y' else 'N' end) slot2,
  max(case when slot = 3 then 'Y' else 'N' end) slot3,
  max(case when slot = 4 then 'Y' else 'N' end) slot4
from tablename
group by name

See the demo.
Results:

| name | slot1 | slot2 | slot3 | slot4 |
| ---- | ----- | ----- | ----- | ----- |
| A    | Y     | Y     | Y     | N     |
| B    | Y     | Y     | N     | N     |

And for the 2nd case use group_concat():

select concat(name, ':', group_concat(slot)) col
from tablename
group by name;

See the demo.
Results:

| col     |
| ------- |
| A:1,2,3 |
| B:1,2   |
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement