0

我在我的应用程序中遇到了一个逻辑问题。我一直在尝试使用 SQL 根据他们的客户 ID 查找分配的成本。我的问题是这样的:在第一个表(Table1)中,我有BusinessUnit、ProductFamily、Cost

在另一个(表2)中,我有BusinessUnit、CustomerID、ProductFamily、Revenue

数据如下`

 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

现在我需要找到每个 CID(Customer_ID) 的分配成本:计算如下

C1 为 BU 分配的成本,Product_Family wise [4,Fiat] = [Table1.Cost(此处值为 145)* Table2.C1 客户的成本(此处值为 50)] / Sum_of_Revenue BU,Product_Family wise [4,菲亚特](这里的值为 170)。

对于 C3 [BU,Product_Family wise (5,TI)],该值应为 (200*40)/(40+80)

请您建议我如何设计我的代码来完成这项任务。

4

3 回答 3

1

尝试以下选择

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 )
;
于 2013-08-01T11:38:51.250 回答
0

尝试

    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 = ...
         ;
于 2013-08-01T11:38:28.600 回答
0

下面的查询对您有用吗?

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
于 2013-08-01T11:43:22.497 回答