簡體   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