Friday, May 23, 2008

Pivot Query in Oracle

I recently revamped some stored procedures I wrote before and found a case where I can apply pivot query to simplify the code. Though I have seen the technique demonstrated in Tom Kyte' Expert One-on-One Oracle(ch.12), this is just another evidence that to know is one thing, to know where to apply is another.

The code I maintained read buy and sell trades from trade table
and sum them into position table for each symbol. Originally, I sumed
buy orders first and then sell orders and stored the results into position table. By using DECODE function, I can finish the task in fewer lines of code. Here is how.

Assuming my trade table and pos table are as follows.
(clieck to enlarge)
image  
I want to sum records in trade table and store the summations in pos table. Using Pivot query as the sql in red square, I can get it done this way.
(clieck to enlarge)
image

This is what I want.
(clieck to enlarge)
image

1 comment:

Unknown said...

The query has become more understandable by drawing tables by KenWu.The notes about other programs are also quite informative.
sap test