跨表的SQL查询计算

时间:2017-09-06 02:54:00

标签: sql sql-server sql-server-2008 percentage

我有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]

enter image description here

我想要的结果是RM_QTYPerUnit,可以通过Excel公式完成:

RM_QTYPerUnit = X_QTY * RM_QTY / SUM(X_QTY)

X_PO_NO的总RM_QTY:VG00181为2320,X_GOODS_CD的RM_QTY:332034960为1094.34而非2320。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要X_PO_NO 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] ; 子句很容易:

X_QTY

如果int值太大而且其总和不适合4字节float,那么将它们以适当的比例投射到decimal或{{1}}并且精度。