Data in Table
order_Day | order_id | prod_id | quantity | price |
---|---|---|---|---|
01-jul-2011 | o1 | p1 | 5 | 5 |
01-jul-2011 | o2 | p2 | 2 | 10 |
01-jul-2011 | o3 | p3 | 10 | 25 |
01-jul-2011 | o4 | p1 | 20 | 5 |
02-jul-2011 | o5 | p3 | 5 | 25 |
02-jul-2011 | o6 | p4 | 6 | 20 |
02-jul-2011 | o7 | p1 | 2 | 5 |
02-jul-2011 | o8 | p5 | 1 | 50 |
02-jul-2011 | o9 | p6 | 2 | 50 |
02-jul-2011 | o10 | p2 | 4 | 10 |
Output Needed
order_Day | prod_id | Sum |
---|---|---|
01-jul-2011 | p3 | 250 |
02-jul-2011 | p3 | 125 |
SELECT * INTO SQL10 FROM ( SELECT '01-jul-2011' order_Day ,'o1' order_id ,'p1' prod_id ,5 quantity ,5 price UNION ALL SELECT '01-jul-2011' ,'o2' ,'p2' ,2 ,10 UNION ALL SELECT '01-jul-2011' ,'o3' ,'p3' ,10 ,25 UNION ALL SELECT '01-jul-2011' ,'o4' ,'p1' ,20 ,5 UNION ALL SELECT '02-jul-2011' ,'o5' ,'p3' ,5 ,25 UNION ALL SELECT '02-jul-2011' ,'o6' ,'p4' ,6 ,20 UNION ALL SELECT '02-jul-2011' ,'o7' ,'p1' ,2 ,5 UNION ALL SELECT '02-jul-2011' ,'o8' ,'p5' ,1 ,50 UNION ALL SELECT '02-jul-2011' ,'o9' ,'p6' ,2 ,50 UNION ALL SELECT '02-jul-2011' ,'o10' ,'p2' ,4 ,10 ) t
Solution 1
SELECT * FROM ( SELECT ps.order_day ,ps.prod_id ,accum_sum ,row_number() OVER ( PARTITION BY ps.order_day ORDER BY accum_sum DESC ) rn FROM SQL10 ps JOIN ( SELECT quantity * price total_amount ,order_day ,order_id ,sum(quantity * price) OVER ( PARTITION BY order_day ,prod_id ORDER BY order_day ,prod_id ) accum_sum FROM SQL10 ) ps1 ON ps.order_day = ps1.order_day AND ps.order_id = ps1.order_id ) t WHERE rn = 1
Solution 2
SELECT Order_Day
,PrOd_id ,SOLD_AMT FROM ( SELECT Order_Day ,PrOd_id ,SUM(quantity * Price) SOLD_AMT ,DENSE_RANK() OVER ( PARTITION BY Order_DaY ORDER BY SUM(quantity * Price) DESC ) RNK FROM SQL10 GROUP BY Order_Day ,PrOd_id ) t1 WHERE RNK = 1;
No comments:
Post a Comment