[英]SQL Statement to name columns based on values in other columns
id | type | email
__________________
1 | ls | example@gmail.com
_________________
1 | sp | example@yahoo.com
_________________
2 | sp | example@live.com
我正在尝试创建一个 SQL 命令,如下所示(伪):
SELECT id 为 'ID',email 其中 type = 'ls' 为 'LS Email',email where type = 'sp' as 'SP Email'
我也尝试过使用 CASE,但似乎无法使其正常工作。 目标是返回如下内容:
ID | LS Email | SP Email
________________________________
1 | example@gmail.com |
1 | | example@yahoo.com
2 | | example@live.com
您可以像这样使用case
表达式:
select
id,
case when type 'ls' then email end ls_email,
case when type 'sp' then email end sp_email
from mytable
如果您希望同一行上相同id
的两个值(这不是您在预期结果中显示的),那么您可以在此之上进行聚合:
select
id,
max(case when type 'ls' then email end) ls_email,
max(case when type 'sp' then email end) sp_email
from mytable
group by id
您可以使用条件聚合:
select id, max(case when type = 'ls' then email end) as ls,
max(case when type = 'sp' then email end) as sp
from t
group by id;
如果您可以有重复项,那么您可能需要使用group_concat()
以便获得所有值:
select id,
group_concat(case when type = 'ls' then email end) as ls,
group_concat(case when type = 'sp' then email end) as sp
from t
group by id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.