如何在mysql中将结果行更改为列

时间:2018-10-12 06:50:03

标签: mysql

我的结果集如下

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

如何显示以下结果

        A. Customer:  1. id,
                      2. name,
                      3. address,
                      4. email,
                      5. phone.

        B. Product :  1. id,
                      2. name,
                      3. stock,
                      4. price.

        C. Order   :  1. id,
                      2. customer_id,
                      3. product_id,
                      4. quantity.

2 个答案:

答案 0 :(得分:1)

使用条件聚合

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

答案 1 :(得分:0)

好象子查询或过程将是一个好主意。 像这样:

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