代码之家  ›  专栏  ›  技术社区  ›  Cosmin

将两个不同表中的几列乘以多个速率(mysql)

  •  0
  • Cosmin  · 技术社区  · 7 年前

    表1-LocTbl

    ID Location Inspections ServiceCalls RegularHrs OTHrs
    1 LA         1             3            7         2
    2 LA         2             4            6         3
    3 LA         5             1            8         1
    

    表2-费率

    Location RateType      Rate
    LA       Inspections    100
    LA       ServiceCalls   42
    LA       RegularHrs     20
    LA       OTHRs          30
    SF       Inspections    110
    SF       ServiceCalls   45
    

    Location InspectionCost ServiceCallCost RegularHrsCost OTHrsCost TotalCost
    LA       800            336             630            120       1886
    

    我需要的是位置表中的每一列总和乘以相应的速率和这些列的总和。类似这样:

    SELECT 
    Sum(Location.Inspections)*Rates.Rate as InspectionCost, 
    Sum(Location.ServiceCalls)*Rates.Rate as ServiceCallCost, 
    Sum(Location.RegularHrs)*Rates.Rate as RegularHrsCost, 
    Sum(Location.OTHRs)*Rates.Rate as OTHrsCost
    [-- >Sum(InspectionCost)+Sum(ServiceCallCost)+Sum(RegularHRsCost)+Sum(OTHrsCost) as TotalCost  <--] 
    ^ how can I calculate the totals for the columns already multiplied?
    FROM Location, Rates
    WHERE Rates.Rate = ? {how do I reference all of the corresponding rates?}
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   etsa    7 年前

    你可以试试这个。我在没有测试的情况下写的(我现在必须回家)。明天我可以帮你做任何错事。

    SELECT A.LOCATION
            , A.T_Inspections*B1.Rate as InspectionCost
            , A.T_ServiceCall*B2.Rate as ServiceCallCost
            , A.T_RegularHrs*B3.Rate as RegularHrsCost
            , A.T_OTHrs*B4.Rate as OTHrsCost
            , A.T_Inspections*B1.Rate + A.T_ServiceCall*B2.Rate+A.T_RegularHrs*B3.Rate+A.T_OTHrs*B4.Rate AS TOTAL_COST
    FROM (SELECT  LOCATION, 
            Sum(Inspections) AS T_Inspections, 
            Sum(ServiceCalls)AS T_ServiceCall, 
            Sum(RegularHrs)AS T_RegularHrs, 
            Sum(OTHRs) AS T_OTHrs   
            FROM Location 
            GROUP BY LOCATION) A
    INNER JOIN RATES B1 ON A.LOCATION = B1.LOCATION AND B1.RATETYPE='Inspections' 
    INNER JOIN RATES B2 ON A.LOCATION = B2.LOCATION AND B2.RATETYPE='ServiceCalls' 
    INNER JOIN RATES B3 ON A.LOCATION = B3.LOCATION AND B3.RATETYPE='RegularHrs' 
    INNER JOIN RATES B4 ON A.LOCATION = B4.LOCATION AND B4.RATETYPE='OTHRs'