将多行组合成一行,包含多列

时间:2016-08-07 19:28:30

标签: mysql

你好我要用字段x选择和分组,但在一行显示几列

SELECT * FROM `cityname` 
WHERE `city`='mashhad' 
group by `city`,`number` 
ORDER BY `city`

enter image description here

但我想要展示:

mashhad  935 915 937 901 

1 个答案:

答案 0 :(得分:0)

由于您希望每个number中的所有city,并在分隔列中显示所有数字,这将是表格轴问题,请尝试以下查询:

SELECT city, 
       MAX(CASE WHEN number = 935 THEN number ELSE NULL END) AS number_935, 
       MAX(CASE WHEN number = 915 THEN number ELSE NULL END) AS number_915, 
       MAX(CASE WHEN number = 937 THEN number ELSE NULL END) AS number_937, 
       MAX(CASE WHEN number = 901 THEN number ELSE NULL END) AS number_901 
FROM   cityname 
GROUP  BY city 

Demo Here