繁体   English   中英

SQL:将行转换为列

[英]SQL: converting rows into columns

我目前有一个如下所示的表:

用户身份 设备ID 设备类型
12_aa 1245 移动的
15_ab 8909 药片
17岁 9090 移动的
18-ac 8900 桌面

我正在尝试将此表转换为以下内容:

用户身份 移动的 药片 桌面
12_aa 1245 无效的 无效的
15_ab 无效的 8909 无效的
17_ya 9090 无效的 无效的
18_ac 无效的 无效的 8900

你能帮助如何实现这一目标吗?

下面使用

select * from `project.dataset.table`
pivot (max(device_id) for device_type in ('mobile', 'tablet', 'desktop'))                    

如果应用于您问题中的样本数据 - 输出是

在此处输入图像描述

您可以使用条件聚合:

select user_id,
       max(case when device_type = 'mobile' then device_id end) as mobile,
       max(case when device_type = 'tablet' then device_id end) as tablet,
       max(case when device_type = 'desktop' then device_id end) as desktop
from t
group by user_id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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