Conventional Way of doing the Pivot in data is as below :
SELECT SUM(DECODE(product_code, 'A', quantity, 0)) AS a_sum_quantity,
SUM(DECODE(product_code, 'B', quantity, 0)) AS b_sum_quantity,
SUM(DECODE(product_code, 'C', quantity, 0)) AS c_sum_quantity
FROM pivot_test
ORDER BY customer_id;
SUM(DECODE(product_code, 'B', quantity, 0)) AS b_sum_quantity,
SUM(DECODE(product_code, 'C', quantity, 0)) AS c_sum_quantity
FROM pivot_test
ORDER BY customer_id;
Using Pivot function (Oracle 11g and above)
Select * from(Select product_code,quantity from pivot_test)pivot (sum(quantity) as Sum_Qty
For (Product_code) in ('A' as AA,'B' as BB, 'C' as CC))
===========================Query Explanation=========================
In the query above, You first select the required columns from the table using Inner query as mentioned in Green.
In the query above, You first select the required columns from the table using Inner query as mentioned in Green.
Then you apply pivot function on the columns selected in inner query.
Aggregate function is applied on the columns whose value you would like to be displayed in the resulting table cells.
as Sum_Qty >> This is optional clause an can be removed. If not removed, you will get output column names as Sum_Qty_AA/_BB etc. If removed, column names would be AA,BB,CC
For (Product_code) >> This clause defines how many columns would be created on the basis of the values provided in the predicates().
For (Product_code) >> This clause defines how many columns would be created on the basis of the values provided in the predicates().
No comments:
Post a Comment