Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 用于将列分组为行的sql查询_Mysql_Sql - Fatal编程技术网

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   |