簡體   English   中英

SQL 語句根據其他列中的值命名列

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM