2016-03-15 264 views
0
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選擇語句,然後總結這2個語句,但我不斷收到錯誤。有任何想法嗎?總結兩個總結語句

+0

你得到了什麼錯誤? \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是[** START **]( http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)瞭解如何提高您的問題質量並獲得更好的答案。 –

+0

那麼現在它是說I1.account不是一個正確的列名稱...我試着做transactions.account = itemtable.account,但它告訴我,它不能綁定 – Femmer

+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 
+0

仍然是同樣的錯誤。 (I1.account = I2.account)列名無效 – Femmer

+0

沒有意義。再次檢查是否有錯別字。嘗試先運行內部選擇,然後檢查列名。 –

+0

隨着你給我的第二選擇,它告訴我消息130,級別15,狀態1,行19 無法對包含聚合或子查詢的表達式執行聚合函數。 – Femmer