2

I have table structure like below :

product          supplier            price            qty
-------          --------            -----            ---
SOAP             ABC                 50               10
SOAP             DCE                 50               10
BRUSH            FGH                 30               5

I would like to transform this table into :

product          supplier_1        supplier_2         price            qty
-------          --------          ----------         -----            ---
SOAP             ABC                 DCE              50               10
BRUSH            FGH                                  30               5

how can I do it in SQL? thanks in advance.

2
  • What would you want shown if the 2nd supplier had a different price for soap? Commented Nov 19, 2014 at 8:31
  • it will be average for price then sum for qty. Commented Nov 19, 2014 at 8:57

2 Answers 2

3

Maybe this helps:

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;
Sign up to request clarification or add additional context in comments.

1 Comment

if you have a maximum number of suppliers per product, you need to add a corresponding number of columns supplier_1 .. supplier_n. There is no dynamic way with static sql (maybe with dynamic sql and plsql).
0
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 or 10G above available.

3 Comments

pivot clause supported in 11G, please note.
So sad, we are still in 10G :(
You can use it fix your problem, I said you could choose another clause "pivot" if you are in 11G

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.