Question

I am stuck with a logical problem in my application. I have been trying to find the allocated cost based on their Customers ID using SQL. My problem goes like this: In first table(Table1) I have BusinessUnit, ProductFamily,Cost

in the other(Table2) I have BusinessUnit, CustomerID, ProductFamily , Revenue

Data as below `

 BU      Product_Family   Cost
 ------------------------------ 
  4      Fiat             145 
  5      TI               200

`

BU  CID Product_Family  Revenue
-----------------------------------
 4  c1    Fiat            50
 4  c2    Fiat            80
 4  c3    Fiat            40
 5   c3         TI               40
 5   c2       TI               80
 Sum_of_Revenue for BU,Product_Family wise [4,Fiat]:               (50+80+40) = 170

Now I need to find the allocated cost per CID(Customer_ID) : Calculation goes like this

Allocated Cost for C1 for BU,Product_Family wise [4,Fiat] = [Table1.Cost(Here the value is 145) * Table2.Cost of C1 Customer(here the value is 50)] / Sum_of_Revenue BU,Product_Family wise [4,Fiat] (here the value is 170).

And for C3 [BU,Product_Family wise (5,TI)]the value should be (200*40)/(40+80)

Would you please suggest me how would I desing my code to accomplish this task.

Was it helpful?

Solution

try following select

select 
BusinessUnit, CustomerID, ProductFamily , Revenue
, (table1.Cost * table2.Revenue ) 
  / (SUM(Revenue) over(partition by table1.BusinessUnit, table1.ProductFamily )) 
                 AS  Allocated_Cost
from 
    table1 
    INNER JOIN table2 ON ( table1.BusinessUnit =  table2.BusinessUnit
                          AND table1.ProductFamily = table2.ProductFamily )
;

OTHER TIPS

try

    SELECT c.cid
         , p.bu
         , p.product_family 
         , p.cost * c.revenue / sor.s   AS allocated_cost
      FROM table1 p
INNER JOIN (
              SELECT bu
                   , product_family
                   , sum(revenue)    AS s
                FROM table2 t2
            GROUP BY bu
                   , product_family
           ) sor
        ON (     sor.bu             = p.bu
             AND sor.product_family = p.product_family )
INNER JOIN table2 c
        ON (     c.bu               = p.bu
             AND c.product_family   = p.product_family )
     WHERE BU = ...
         ;

Would something like the below query work for you?

WITH cust_total_rev AS (
SELECT CID
, SUM(Revenue) AS total_rev
FROM Table2
GROUP BY CID
)
SELECT CID
, (t1.Cost * t2.Revenue)/ctr.total_rev AS Allocated_Cost
FROM Table1 t1
JOIN Table2 t2 ON t1.BU = t2.BU
JOIN cust_total_rev ctr ON ctr.CID = t2.CID
GROUP BY t2.CID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top