在包含聚合或子查询的表达式上执行聚合函数的问题

时间:2012-08-10 12:20:49

标签: sql

select 
    A.ACCT as acct, COUNT(TRANS_key) as payments
from 
    DEBT A 
join 
    TRANS B on B.DEBT_KEY = A.DEBT_KEY
join 
    TRANS_CODE C on C.TRANS_CODE = B.TRANS_CODE
join 
    CLIENT D on D.CLIENT_KEY = A.CLIENT_KEY
join 
    STATUS S on S.STAT_KEY = A. STAT_KEY
where 
    S.CATEGORY = 'A' and D.CLIENT_KEY = 43

错误:

  

无法对包含的表达式执行聚合函数   聚合或子查询。

运行此时我收到上述错误。我不确定我是否应该以不同方式加入这些表格,但我需要这个才能正常工作。

2 个答案:

答案 0 :(得分:0)

select A.ACCT as acct, COUNT(TRANS_key) as payments
from DEBT A 
join TRANS B on B.DEBT_KEY = A.DEBT_KEY
join TRANS_CODE C on C.TRANS_CODE = B.TRANS_CODE
join CLIENT D on D.CLIENT_KEY = A.CLIENT_KEY
join STATUS S on S.STAT_KEY = A. STAT_KEY
where S.CATEGORY = 'A' and D.CLIENT_KEY = 43
group by A.ACCT 

您不能使用像count那样只返回1个结果的聚合函数和一个返回多个的select。如果您想要计算每个a.acct的计数,请执行以上操作。

答案 1 :(得分:0)

所有其他选择必须分组。使用此

    select A.ACCT as acct, COUNT(TRANS_key) as payments

from DEBT A join TRANS B on B.DEBT_KEY = A.DEBT_KEY

join TRANS_CODE C on C.TRANS_CODE = B.TRANS_CODE

join CLIENT D on D.CLIENT_KEY = A.CLIENT_KEY

join STATUS S on S.STAT_KEY = A. STAT_KEY

where S.CATEGORY = 'A' and D.CLIENT_KEY = 43
GROUP BY A.ACCT