Mysql 用于将列分组为行的sql查询
我有这样的桌子Mysql 用于将列分组为行的sql查询,mysql,sql,Mysql,Sql,我有这样的桌子 Name Slot A 1 A 2 A 3 B 1 B 2 我想进行查询,结果如下 Name slot1 slot2 slot3 slot4 A Y Y Y N B Y Y N N 或 我试着使用分组方式,但我不知道如何
Name Slot
A 1
A 2
A 3
B 1
B 2
我想进行查询,结果如下
Name slot1 slot2 slot3 slot4
A Y Y Y N
B Y Y N N
或
我试着使用分组方式,但我不知道如何获得插槽号
请帮忙,谢谢 使用分组讨论:
使用条件聚合:
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
看。
结果:
对于第二种情况,使用组_concat:
看。
结果:
SELECT name, GROUP_CONCAT(Slot)
FROM table t
GROUP BY name;
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
| name | slot1 | slot2 | slot3 | slot4 |
| ---- | ----- | ----- | ----- | ----- |
| A | Y | Y | Y | N |
| B | Y | Y | N | N |
select concat(name, ':', group_concat(slot)) col
from tablename
group by name;
| col |
| ------- |
| A:1,2,3 |
| B:1,2 |