Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL Cross Tab Query

I have a table which has the following structure and sample data:

ITEM   LOC   STOCK
0001   KS5    10
0001   KS6    30
0002   KS5    10
0002   KS6    20

I need to query cross tab so that I get

ITEM  KS5  KS6
0001  10   30
0002  10   20

The LOC (KS5 and KS6) can vary and new locations can be added.

How can I get the desired result?

like image 349
Imran Hemani Avatar asked Nov 27 '25 23:11

Imran Hemani


1 Answers

Please try this query .

SELECT *
FROM   (SELECT ITEM ,LOC ,STOCK
        FROM   TABLE_NAME)
PIVOT  (SUM(STOCK) FOR (LOC) IN ('KS5' , 'KS6'))
ORDER BY ITEM;

Regards.

like image 129
Jerry Avatar answered Nov 30 '25 13:11

Jerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!