根据SQL中的2个计算列来计算字段

时间:2017-07-13 14:29:57

标签: sql join subquery inner-join calculated-columns

我有一个查询,它根据称为工作单元的公共标识符对几个值求和。我试图弄清楚如何添加一个以百分比计算此公式的列:(SumOfAct - SumOfStd)/(SumOfStd)

我在想某种带内连接的子查询是可行的,但我不确定如何让它看起来正确。

这是我的代码,除了计算列之外,它还能获得我想要的所有内容:

SELECT v_MES_OrderIssues.AssignedWorkcell
 , CONVERT(Decimal(10,2), Sum(v_SAP_OrderOperations.Std)) AS SumOfStd
 , CONVERT(Decimal(10,2), Sum(v_SAP_OrderOperations.Act)) AS SumOfAct
 , CONVERT(Decimal(10,2), Sum(v_SAP_OrderOperations.Variance)) AS SumOfVariance

FROM (v_SAP_OrderOperations 
LEFT JOIN v_SAP_Orders ON v_SAP_OrderOperations.Ordr = v_SAP_Orders.Ordr) 
LEFT JOIN v_MES_OrderIssues ON v_SAP_OrderOperations.Ordr = v_MES_OrderIssues.WOrder
WHERE (((v_SAP_Orders.OpenOrder) Like '1')
AND ((v_SAP_Orders.Equipment) Is Not NULL)
AND ((v_SAP_OrderOperations.ACT)>0))
AND ((v_MES_OrderIssues.AssignedWorkcell) Like 'S5H%W')
AND ((v_MES_OrderIssues.DateTimeClosed) Is Null)
OR (((v_SAP_Orders.OpenOrder) Like '1')
AND ((v_SAP_Orders.Equipment) Is Not NULL)
AND ((v_SAP_OrderOperations.OpenOp) Like '0'))
AND ((v_MES_OrderIssues.AssignedWorkcell) Like 'S5H%W')
AND ((v_MES_OrderIssues.DateTimeClosed) Is Null)

GROUP BY v_MES_OrderIssues.AssignedWorkcell

ORDER BY Sum(v_SAP_OrderOperations.Variance) DESC

1 个答案:

答案 0 :(得分:0)

如果我做对了你可以直接在SELECT子句

中做到
SELECT v_MES_OrderIssues.AssignedWorkcell
 , CONVERT(Decimal(10,2), Sum(v_SAP_OrderOperations.Std)) AS SumOfStd
 , CONVERT(Decimal(10,2), Sum(v_SAP_OrderOperations.Act)) AS SumOfAct
 , CONVERT(Decimal(10,2), Sum(v_SAP_OrderOperations.Variance)) AS SumOfVariance
 , CONVERT(Decimal(10,2), (Sum(v_SAP_OrderOperations.Act) - Sum(v_SAP_OrderOperations.Std))/ Sum(v_SAP_OrderOperations.Std)) AS percentage
...

BTW,

LEFT JOIN v_SAP_Orders 
...
WHERE (((v_SAP_Orders.OpenOrder) Like '1')

INNER JOIN实际上因为左连接表表达式中的列因此被禁止具有NULL值。您可能希望将谓词移动到ON子句以使其保持左连接状态。