如何将一个SQL列显示为两个独立的列
我有一个存储电话号码和电话类型的SQL表,customer_id是一个与customer表相关的外键如何将一个SQL列显示为两个独立的列,sql,sqlite,pivot-table,Sql,Sqlite,Pivot Table,我有一个存储电话号码和电话类型的SQL表,customer_id是一个与customer表相关的外键 NumberID | phone_number | phone_type|customer_id 1 | 011111 | phone1 |1 2 | 022222 | phone2 |1 我试图用sqlite显示如下 customer_id| phone1 |phone2 1| 011
NumberID | phone_number | phone_type|customer_id
1 | 011111 | phone1 |1
2 | 022222 | phone2 |1
我试图用sqlite显示如下
customer_id| phone1 |phone2
1| 011111 |022222
我不确定正确的方法是什么,我应该使用自连接吗?使用条件聚合:
SELECT
customer_id,
MAX(CASE WHEN phone_type = 'phone1' THEN phone_number END) phone1,
MAX(CASE WHEN phone_type = 'phone2' THEN phone_number END) phone2
FROM mytable
GROUP BY customer_id
select customer_id,
max(case when phone_type = 'phone1' then phone_number end) as phone1,
max(case when phone_type = 'phone2' then phone_number end) as phone2
from t
group by customer_id;
您可以使用条件聚合:
SELECT
customer_id,
MAX(CASE WHEN phone_type = 'phone1' THEN phone_number END) phone1,
MAX(CASE WHEN phone_type = 'phone2' THEN phone_number END) phone2
FROM mytable
GROUP BY customer_id
select customer_id,
max(case when phone_type = 'phone1' then phone_number end) as phone1,
max(case when phone_type = 'phone2' then phone_number end) as phone2
from t
group by customer_id;
如果客户有三个、四个。。。还是20部电话?你想要20列吗?我发现了另一个同样用sqlite标记的问题,它展示了做透视表的一般技术。另一个问题也涉及sum(),它与您的案例无关,但在其他方面是适用的。这项技术在其他品牌的SQL数据库中是相同的,因此您可以按照标签找到其他答案。欢迎@Nathan!如果我的回答正确回答了你的问题,请点击绿色的复选标记。。。谢谢