我希望有人可以帮助我快速解决这个问题。出于某种原因,我只是不知道如何将我的表格与某些费率相乘。这就是我所面对的:
表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?}
有人可以帮我提一些直接的建议,告诉我如何才能达到我想要的结果。欢迎任何解决方法。
答案 0 :(得分:1)
你可以试试这个。我把它写成了白色测试(我现在必须回家)。对于任何错误我明天都可以帮到你。
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'