简体   繁体   English

如何在不使用SQL Server / MS Access使用所有选定列的情况下进行分组和求和?

[英]How can I group by and sum without using all selected columns using SQL Server/MS Access?

SQL newbie here... SQL新手在这里...

Here's a sample of my table named TEST in MS Access: 这是我在MS Access中名为TEST的表的示例:

EFF_DATE   BATCH   ENTITY ACCOUNT  TRANS_AMT
12/1/2017  TEST A  110    165105   (10.00)
12/1/2017  TEST A  120    278910    10.00 
12/1/2017  TEST A  110    165105   (10.00)
12/1/2017  TEST A  120    165135    10.00 
12/2/2017  TEST B  120    165135    15.00 
12/2/2017  TEST B  110    278910   (10.00)

In my query, I'm trying to sum by EFF_DATE and BATCH only and exclude TRANS_AMT sums equaling 0. 在我的查询中,我尝试仅通过EFF_DATE和BATCH求和,并排除等于0的TRANS_AMT和。

So my query results should be the following: 因此,我的查询结果应为以下内容:

EFF_DATE   BATCH   ENTITY  ACCOUNT  TRANS_AMT
12/2/2017  TEST B  120     165135   15.00 
12/2/2017  TEST B  110     278910  (10.00)

I've tried the following query: 我尝试了以下查询:

SELECT 
EFF_DATE, 
BATCH, 
ENTITY, 
ACCOUNT, 
Sum(TRANS_AMT) 
FROM TEST
WHERE ACCOUNT in ("165105","278910","165135")
AND ENTITY in ("120","110")
GROUP BY TEST.EFF_DATE, TEST.BATCH
HAVING (((Sum(TRANS_AMT))<>0));

I get the following error: 我收到以下错误:

"You tried to execute a query that does not include the specified expression 'ENTITY' as part of an aggregate function." “您试图执行一个不包含指定表达式'ENTITY'作为聚合函数一部分的查询。”

When I googled the error I couldn't find any information other than stating that the other columns should be added to the GROUP BY clause but if I add them, then the transactions that should sum to zero by date and batch continue to show up. 当我搜索错误时,除了声明应将其他列添加到GROUP BY子句外,我找不到任何其他信息,但是如果我添加它们,则按日期和批次求和的事务将继续显示为零。 Any ideas on what I can do to get the desired result? 关于我可以做什么以获得预期结果的任何想法?

Thanks, Dan 谢谢,丹

修改您的GROUP BY,并包括ENTITY和ACCOUNT

GROUP BY TEST.EFF_DATE, TEST.BATCH, ENTITY, ACCOUNT

When you use something in a grouped select statement, it needs to be in the group by. 当您在分组的select语句中使用某些内容时,它必须位于group by中。

However, you can do this nesting. 但是,您可以执行此嵌套。

You can all the effective date/batch combinations and are non-zero. 您可以将所有有效的日期/批次组合设为非零值。

Then only select outer records pertaining to them. 然后仅选择与其相关的外部记录。

SELECT * FROM TEST A
WHERE (A.EFF_DATE, A.BATCH) IN
(
    SELECT B.EFF_DATE, B.BATCH
    FROM TEST B
    GROUP BY B.EFF_DATE, B.BATCH
    HAVING Sum(B.TRANS_AMT)<>0
)

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

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