简体   繁体   English

SQL Server 2005汇总查询

[英]SQL Server 2005 summation query

I'm trying to create a query on SQL server 2005 that will check if the sum of some fields in some detail records is equal to the total field in a header record. 我正在尝试在SQL Server 2005上创建一个查询,该查询将检查某些详细记录中某些字段的总和是否等于标头记录中的总字段。 This will be used for creating electronic deposit of checks for the company I'm working for. 这将用于为我工作的公司创建电子支票存款。

The hierarchy looks like this: Deposits --> Batches --> Checks 层次结构如下所示:存款->批次->支票

Before creating the file for electronic deposit, replication might not have fully completed for each table, so I need to check to ensure that each record is there before creating the file. 在创建用于电子存款的文件之前,可能没有为每个表完全完成复制,因此在创建文件之前,我需要检查以确保每个记录都在其中。 Basically, I want to select a list of locations and ids from my Deposits table where the correct number of batches and the correct number of checks do exist in their respective tables. 基本上,我想从我的“存款”表中选择一个位置和ID的列表,其中在各自的表中确实存在正确的批次数量和正确的支票数量。

Here is the logic that I want to have. 这是我想要的逻辑。

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

The above doesn't work because you can't have the aggregate function sum in the where clause. 上面的方法不起作用,因为您无法在where子句中使用聚合函数sum。 I can easily do this programatically, but if there is a clever way to do this quickly in a SQL statement, that would be best. 我可以很容易地以编程方式执行此操作,但是如果有聪明的方法可以在SQL语句中快速执行此操作,那将是最佳选择。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Thanks! 谢谢!

You can move your sum check to the having clause, after the where clause: 您可以将总和检查移到where子句之后的hading子句中:

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

You can't do a sum in a WHERE clause, but you can use the HAVING clause. 您不能在WHERE子句中求和,但是可以使用HAVING子句。 for example 例如

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

replication might not have fully completed for each table ! 每个表的复制可能尚未完全完成 surely this is the problem that needs addressing instead of a work around record count check. 当然,这是需要解决的问题,而不是解决记录计数检查的问题。

How are you replicating the data? 您如何复制数据?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM