oraclesql:透视列
我的表格结构如下:oraclesql:透视列,sql,oracle,oracle10g,Sql,Oracle,Oracle10g,我的表格结构如下: product supplier price qty ------- -------- ----- --- SOAP ABC 50 10 SOAP DCE 50 10 BRUSH
product supplier price qty
------- -------- ----- ---
SOAP ABC 50 10
SOAP DCE 50 10
BRUSH FGH 30 5
我想将此表转换为:
product supplier_1 supplier_2 price qty
------- -------- ---------- ----- ---
SOAP ABC DCE 50 10
BRUSH FGH 30 5
如何在SQL中实现这一点?提前谢谢
select product,supplier_1,supplier_2,price,qty from table
model
return all rows
dimension by(product)
measures(supplier,
lpad(' ',10) supplier_1,
lpad(' ',10) supplier_2
)
rules upsert(
supplier_1[0] = supplier['SOAP'],
supplier_2[0] = supplier['BRUSH']
)
10G或10G以上可用。这可能有助于:
select product,
max(case when rn = 1 then supplier end) as supplier_1,
max(case when rn = 2 then supplier end) as supplier_2,
-- ...
-- max(case when rn = n then supplier end) as supplier_n,
avg(price) as price,
sum(qty) as sum
from(select t.*,
row_number() over (partition by product order by supplier) rn
from your_table t
)
group
by product;
请注意,11G中支持pivot子句。很遗憾,我们仍然在10G中:(您可以使用它解决您的问题,我说过您可以选择另一个子句“pivot”如果您在11G中,如果第二个供应商的soap价格不同,您希望显示什么?它将是价格的平均值,然后是数量的总和。如果每个产品的供应商数量最大,您需要添加相应数量的列supplier\u 1..supplier\n。静态sql没有动态方式(可能使用动态sql和plsql).谢谢你的回答^^