需要列值分散在多个列中
Posted
技术标签:
【中文标题】需要列值分散在多个列中【英文标题】:Need column values to be dispersed among multiple columns 【发布时间】:2020-05-10 11:25:38 【问题描述】:我有两张表如下:
SQL> select * from customer;
CUSTOMERID CUSTOMERNAME
---------- --------------
1 A
2 B
SQL> 从汽车中选择 *;
CARID CUSTOMERID MODEL
---------- ---------- ----------
1 1 toyota
2 1 honda
3 2 suzuki
我需要编写一个 SQL 查询,它会给出如下输出: (我们可以为此使用 PIVOT 或 UNPIVOT 吗?我不确定!)
CUSTOMERID CUSTOMERNAME Model1 Model2
---------- ------------- ------- --------
1 A toyota honda
2 B suzuki NULL
【问题讨论】:
用您正在使用的数据库标记您的问题。 【参考方案1】:您可以使用窗口函数并进行条件聚合:
select customerid, customername,
max(case when seq = 1 then model end) as model1,
max(case when seq = 2 then model end) as model2
from (select c.*, cr.model,
row_number() over (partition by c.customerid order by cr.MODEL) as seq
from customer c inner join
cars cr
on cr.customerid = c.customerid
) t
group by customerid, customername;
【讨论】:
【参考方案2】:如果你只有两个值,你可以使用聚合:
select cu.customerid, cu.customername,
min(ca.model) as model1,
nullif(max(ca.model), min(ca.model)) as model2
from customers cu join
cars ca
on ca.customerid = cu.customerid
group by cu.customerid, cu.customername;
如果你有一个不确定的数字,我建议将它们聚合成一个字符串或数组。该语法取决于数据库,但典型的语法是:
select cu.customerid, cu.customername,
listagg(ca.model, ',') within group (order by ca.model) as models
from customers cu join
cars ca
on ca.customerid = cu.customerid
group by cu.customerid, cu.customername;
【讨论】:
以上是关于需要列值分散在多个列中的主要内容,如果未能解决你的问题,请参考以下文章