我正在尝试通过将产品表链接到具有3对多表的特征表来对产品进行建模
例如
从这种结构中,我尝试将其返回到一个结果,以将具有特征和类型特征的值显示在选择语句中。
例如:
select distinct
p.ProductId, p.name, p.description, p.brand, p.model, body, DoorNum
from
Product p
left join
ProductionCharacteristic pc on p.ProductId = pc.ProductId,
(select CharacteristicId, "'Body'" as body, "'DoorNum'" as DoorNum
from Characteristic c
pivot (max(c.name) for c.type IN ('Body' , 'DoorNum'))) temp
where
pc.CharacteristicId = temp.CharacteristicId
问题1:any_Value是汇总函数吗?它枢轴不喜欢它,我改用max() 问题2:以上选择返回3行。有没有办法将其压缩到一个记录?
答案 0 :(得分:0)
JOIN
和LEFT JOIN
,则不要使用 ,
,反之亦然。select
p.ProductId
, p.name
, p.description
, p.brand
, p.model
, listagg(temp.body,', ') as body
, listagg(temp.DoorNum,', ') as doornum1
, arrayagg(temp.DoorNum) as doornum2
from
Product p
left join
ProductionCharacteristic pc
on p.ProductId = pc.ProductId
join (
select CharacteristicId, body, doornum
from Characteristic c
pivot (max(c.name) for c.type IN ('Body' , 'DoorNum')) as p (CharacteristicId, value, body, doornum)
) temp
on pc.CharacteristicId = temp.CharacteristicId
group by 1,2,3,4,5
;
with temp as (
select CharacteristicId, body, doornum
from Characteristic c
pivot (max(c.name) for c.type IN ('Body' , 'DoorNum')) as p (CharacteristicId, value, body, doornum)
)
select
p.ProductId
, p.name
, p.description
, p.brand
, p.model
, listagg(temp.body,', ') as body
, listagg(temp.DoorNum,', ') as doornum1
, arrayagg(temp.DoorNum) as doornum2
from
Product p
left join
ProductionCharacteristic pc
on p.ProductId = pc.ProductId
join temp
on pc.CharacteristicId = temp.CharacteristicId
group by 1,2,3,4,5
;
select
p.ProductId
, p.name
, p.description
, p.brand
, p.model
, temp.body
, temp.doornum1
, temp.doornum2
from
Product p
join lateral (
select listagg(iff(type = 'Body',name,null),', ') as body
,listagg(iff(type = 'DoorNum',name,null),', ') as doornum1
,arrayagg(iff(type = 'DoorNum',name,null)) as doornum2
from Characteristic c
join ProductionCharacteristic pc
on pc.CharacteristicId = c.CharacteristicId
where p.ProductId = pc.ProductId
) temp
;
希望这会有所帮助。