MySQL如何按多维度查询数据?

问题:现有一张表,有ID/City/Level三个字段,如何通过查询语句生成如下结果?

表:
ID City Level
1 SH 7
2 SH 6
3 BJ 6
4 BJ 7
5 SZ 6

结果:
Level SH BJ SZ
6 1 1 1
7 1 1 0

看不出你的目标结果有什么规律,如果需要这样的话,考虑用存储过程或者其他语言遍历表结果来处理。

直接手敲的,可能会有bug

select
p.level,
sum(case when city = 'SH' then num else 0 end) SH,
sum(case when city = 'BZ' then num else 0 end) BZ,
sum(case when city = 'SZ' then num else 0 end) SZ
from
(
select 
city,
level,
count(1) num
from test
group by 
city,
level) p
group by 
p.level;