两个总和报表的总和

时间:2016-03-15 14:57:35

标签: sql-server-2008 sum

DECLARE @aracct VARCHAR(12)
    SET @aracct = '49920813'
DECLARE @item_no VARCHAR(12)
    SET @item_no = '2319'
SELECT tran_id, * FROM transactions
    WHERE account = @aracct AND item_no = @item_no
/*-----------Use if removing certain items from a check-----------*/
CREATE TABLE itemtable (items VARCHAR(6), account VARCHAR(12))
    INSERT INTO itemtable VALUES ('2299', @aracct)
    INSERT INTO itemtable VALUES ('2300', @aracct)
    --INSERT INTO @itemtable VALUES ('')
DECLARE @tran_id_pmt VARCHAR(6)
    SET @tran_id_pmt = '209413'

SELECT I1.result - I2.result AS 'final result'
FROM (SELECT SUM(amt_paid) AS result
      FROM transactions 
      WHERE account = @aracct AND item_no = @item_no) AS I1
JOIN (SELECT SUM(amt_paid) AS result
      FROM transactions 
      WHERE account = @aracct AND item_no = (SELECT items FROM itemtable)) AS I2
  ON (I1.account = I2.account)

尝试获取总和2选择语句然后对这两个语句求和,但我一直收到错误。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要在子查询中加入account,以便在ON条件

上使用它
SELECT I1.result - I2.result AS 'final result'
FROM (SELECT account, SUM(amt_paid) AS result
             ^^^^^^^
      FROM transactions 
      WHERE account = @aracct AND item_no = @item_no
      GROUP BY account) AS I1
      ^^^^^^^^^^^^^^^^
JOIN (SELECT account, SUM(amt_paid) AS result
      FROM transactions 
      WHERE account = @aracct AND item_no = (SELECT items FROM itemtable)
      GROUP BY account) AS I2
  ON (I1.account = I2.account)
         ^^^^^^^^

您也可以使用条件聚合来解决它。

SELECT SUM(CASE WHEN item_no = @item_no THEN amt_paid
                                        ELSE 0
           END)
       -
       SUM(CASE WHEN item_no IN (SELECT items FROM itemtable) THEN amt_paid
                                                              ELSE 0
           END) AS 'final result'          
FROM Transactions
WHERE account = @aracct