简体   繁体   中英

How to change result row into column in mysql

I have below result set

Name  |   ID |  Total |  CityName
--------------------------------
A         1       2        ABC
--------------------------------
B         2       1        XYZ
--------------------------------
C         3       1        ABC
--------------------------------

How I can show below result

Name |  ID  |   ABC |  XYZ
---------------------------
A       1        2      0
---------------------------
B       2        0      1
---------------------------
C       3        1      0
---------------------------

Use conditional aggregation

select name, id, max(case when CityName='ABC' then total else 0 end) as ABC
max(case when CityName='XYZ' then total else 0 end) as XYZ
from tablename
group by name,id

Well it seems like a subquery, or procedure would be a good idea. Something like:

select Name,ID,
(select Total from tets where CityName ='ABC' and Id = t.Id) as 'ABC',
(select Total from tets where CityName ='XYZ' and Id = t.Id) as 'XYZ'
from tets t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM