在 mysql 中将列转置为行
transpose column to row in mysql
我想在不使用 MYSQL 中的排名方法的情况下将结果列转置为行。
select pid , phone from mt where pid = 1 ;
Result :
pid phone
1 556
1 678
我想要这种格式:
pid phone1 phone2
1 556 678
类似地,如果执行一个只有 1 个值的查询,如下所示
select pid , phone from mt where pid = 2 ;
它应该导致 phone1 和 phone2 列,但 phone2 列应该为空,如下所示。
pid phone1 phone2
2 123 NULL
如何进行下一步?
如果只有两个值,可以使用min()
和max()
:
select pid, min(phone) as phone_1,
(case when min(phone) <> max(phone) then max(phone) end) as phone_2
from t
group by pid;
我想在不使用 MYSQL 中的排名方法的情况下将结果列转置为行。
select pid , phone from mt where pid = 1 ;
Result :
pid phone
1 556
1 678
我想要这种格式:
pid phone1 phone2
1 556 678
类似地,如果执行一个只有 1 个值的查询,如下所示
select pid , phone from mt where pid = 2 ;
它应该导致 phone1 和 phone2 列,但 phone2 列应该为空,如下所示。
pid phone1 phone2
2 123 NULL
如何进行下一步?
如果只有两个值,可以使用min()
和max()
:
select pid, min(phone) as phone_1,
(case when min(phone) <> max(phone) then max(phone) end) as phone_2
from t
group by pid;