2017-09-18 15 views
-1

私のSQL文では、MAX()を使用して最終取引日を検索しようとしていますが、エラーが発生していました。 (エラー状態など)HAVING句にMAX句のwhere句の使用方法

Msg 147, Level 15, State 1, Line 11 
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference. 
+0

@Tab Alleman、それは私の質問にどのように関連していますか? –

答えて

1

移動それは:

ここ
select 
c.branch, c.cust_no, c.name, c.dobirth, c.cust_sex,c.address, c.phone, c.group_name, c.group_code, c.INCOR_DATE, 
(l.branch+l.gl_no+l.ac_no) as cust, SUM(l.loan_amt) as lamt, l.ac_no, l.cycle, l.exp_date, l.inst_type, l.trx_no, 
l.ln_period, l.full_paid, l.Class_Age, l.disb_date, max(h.trx_date) as last_trx, 
(h.principal + h.interest) as instalment, (h.principal + h.interest) as overdue, 
h.trx_date 

from customer c, loans l, loanhist h 

where c.cust_no = l.ac_no and l.full_paid != 1 and c.cust_no = h.ac_no and MONTH(h.trx_date) = MONTH(GETDATE()) 
and YEAR(h.trx_date) = YEAR(GETDATE()) and h.trx_type != 'lp' and h.trx_date = MAX(h.trx_date) 

group by c.branch, c.cust_no, c.name, c.dobirth, c.cust_sex,c.address, c.phone, c.group_name, c.group_code, c.INCOR_DATE, 
l.ac_no, l.cycle, l.exp_date, l.inst_type, l.trx_no, 
l.ln_period, l.full_paid, l.Class_Age, 
l.disb_date, l.branch,l.gl_no, h.principal, h.interest, h.trx_date 

それが私に与えていたエラーは次のとおりです。

は、ここに私のクエリです。

によってグループの後に発生します。

having h.trx_date = MAX(h.trx_date) 
0

あなたはそのために設計されたHAVING句、使用する必要があります。

HAVING h.trx_date = MAX(h.trx_date) 

をそして、あなたはGROUP BY句の下に置きます。

+0

downvotingの特別な理由はありますか? – sagi