[英]SQL Query calculation across tables
I have 3 tables that are joined using the following query: 我有3个表,使用以下查询进行联接:
SELECT
b.[_PRESS_INST_NO]
,a.[X_PO_NO]
,a.[X_GOODS_CD]
,a.[X_QTY]
,c.RM_CD
,c.RM_QTY
FROM
T1 a
INNER JOIN T2 b ON a.X_PO_NO=b.X_PO_NO
INNER JOIN T3 c ON b._PRESS_INST_NO=c.[_PRESS_INST_NO]
My desired result is RM_QTYPerUnit
that can be done by Excel formula: 我想要的结果是
RM_QTYPerUnit
,可以通过Excel公式完成:
RM_QTYPerUnit = X_QTY * RM_QTY / SUM(X_QTY)
Total RM_QTY of X_PO_NO: VG00181 is 2320, and RM_QTY for X_GOODS_CD : 332034960 is 1094.34 not 2320. X_PO_NO:VG00181的总RM_QTY是2320,而X_GOODS_CD的RM_QTY:332034960是1094.34而不是2320。
If I understood you correctly, you need SUM
partitioned by X_PO_NO
. 如果我对您的理解正确,则需要将
SUM
划分为X_PO_NO
。 It is easy to get using the OVER
clause: 使用
OVER
子句很容易:
SELECT
b.[_PRESS_INST_NO]
,a.[X_PO_NO]
,a.[X_GOODS_CD]
,a.[X_QTY]
,c.RM_CD
,c.RM_QTY
,a.[X_QTY] * c.RM_QTY /
SUM(CAST(a.[X_QTY] AS float)) OVER (PARTITION BY a.X_PO_NO) AS RM_QTYPerUnit
FROM
T1 a
INNER JOIN T2 b ON a.X_PO_NO=b.X_PO_NO
INNER JOIN T3 c ON b._PRESS_INST_NO=c.[_PRESS_INST_NO]
;
If the X_QTY
values are so large that their sum doesn't fit into 4-byte int
, then cast them to float
or decimal
with appropriate scale and precision. 如果
X_QTY
值太大,以至于它们的总和不适合4字节int
,则将它们转换为具有适当decimal
和精度的float
或decimal
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.