将两个查询联接到一个表并减去值

时间:2019-10-31 08:20:22

标签: sql join pivot

我需要将这两个输出值(Add_sumMinus_sum)放在一张表中并减去(Add_sum - Minus_sum)并显示该值。

我尝试了许多其他选项,子查询等,但无法正常工作。

查询1:

SELECT        I.ItemCode, COUNT(H.TransactionTypeID) AS ADD_Sum
FROM            inMoveHd AS H INNER JOIN
                         inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
                         inItem AS I ON I.ItemID = L.ItemID INNER JOIN
                         inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE        (T.TransactionSign = 1)
GROUP BY I.ItemCode

查询2:

SELECT        I.ItemCode, COUNT(H.TransactionTypeID) AS Minus_Sum
FROM            inMoveHd AS H INNER JOIN
                         inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
                         inItem AS I ON I.ItemID = L.ItemID INNER JOIN
                         inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE        (T.TransactionSign = -1)
GROUP BY I.ItemCode

2 个答案:

答案 0 :(得分:1)

使用case表达式进行条件聚合

SELECT  I.ItemCode,
        COUNT(case when T.TransactionSign = 1 then H.TransactionTypeID end) AS ADD_Sum,
        COUNT(case when T.TransactionSign = -1 then H.TransactionTypeID end) AS Minus_Sum
FROM      inMoveHd AS H INNER JOIN
                   inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
                   inItem AS I ON I.ItemID = L.ItemID INNER JOIN
                   inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE  (T.TransactionSign = -1 or T.TransactionSign = 1)
GROUP BY I.ItemCode

答案 1 :(得分:1)

我认为您正在寻找条件聚合:

SELECT        
    I.ItemCode, 
    SUM(CASE WHEN T.TransactionSign = 1  THEN 1 ELSE 0 END) AS Add_Sum,
    SUM(CASE WHEN T.TransactionSign = -1 THEN 1 ELSE 0 END) AS Minus_Sum,
    SUM(T.TransactionSign) difference
FROM 
    inMoveHd AS H INNER JOIN
    inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
    inItem AS I ON I.ItemID = L.ItemID INNER JOIN
    inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE  T.TransactionSign IN (-1, 1)
GROUP BY I.ItemCode