2009-07-08 125 views
1

我想在SQL服務器2005上創建一個查詢,它將檢查某些詳細記錄中某些字段的總和是否等於標題記錄中的總字段。這將用於爲我工作的公司創建電子支票存款。SQL Server 2005求和查詢

層次結構如下所示: 存款 - >批次 - >檢查

創建電子存款的文件之前,複製可能沒有完全完成每個表,所以我需要檢查,以確保每個記錄在創建文件之前都在那裏。基本上,我想從我的Deposits表中選擇一個位置和ID列表,其中正確的批次數量和正確的檢查次數確實存在於它們各自的表格中。

這是我想要的邏輯。

select location, d.id from closing_balance..cb_deposits as d 
left outer join closing_balance..cb_checkbatchhf as b on d.id = b.deposit_id and d.location = b.loc 
left outer join closing_balance..cb_checkdf as c on b.id = c.batch_id and b.loc = c.loc 
where sum(c.check_amt) = b.scanned_subtotal and sum(b.scanned_subtotal) = d.amount and sum(b.num_checks_scanned) = d.count 

上述不起作用,因爲你不能在where子句中的聚合函數總和。我可以用編程方式輕鬆完成這個任務,但是如果在SQL語句中有一個聰明的方法可以快速完成此操作,那最好。

任何幫助是極大的讚賞。

謝謝!

+0

記住:WHERE - 從任何考慮因素中刪除行,GROUP BY對其餘行進行分組,並且HAVING刪除組 – 2009-07-08 15:22:34

回答

4

您可以將您和檢查having子句,where子句後:

select location, d.id 
from closing_balance..cb_deposits as d 
left outer join closing_balance..cb_checkbatchhf as b 
    on d.id = b.deposit_id and d.location = b.loc 
left outer join closing_balance..cb_checkdf as c 
    on b.id = c.batch_id and b.loc = c.loc 
group by location, d.id, b.scanned_subtotal, d.amount, d.count 
having sum(c.check_amt) = b.scanned_subtotal 
    and sum(b.scanned_subtotal) = d.amount 
    and sum(b.num_checks_scanned) = d.count 
+0

謝謝。這工作。 – Aaron 2009-07-08 15:31:19

1

您不能在WHERE子句中進行求和,但可以使用HAVING子句。例如

SELECT 
    Id 
FROM 
    Table 
GROUP BY 
    Id 
HAVING 
    SUM(Amount) = 100 
1

複製可能沒有完全完成每個表!當然這是需要解決的問題,而不是圍繞記錄計數檢查的工作。

你如何複製數據?

+0

我不同意。有38個位置將數據複製到將生成文件的中央位置。如果出現網絡錯誤或者存在延遲問題或者導致進程的一部分未被複制並且文件被創建的任何部分,則該文件在被髮送到銀行用於電子存儲時將失敗。這不是一個解決方法...這是一個檢查,以確保所有的數據實際上存在。 – Aaron 2009-07-08 15:53:27