在我的sql语句中,我正在尝试使用MAX()
查找最后一个交易日期,但我收到了错误。
这是我的问题:
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
这是给我的错误:
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 :(得分:1)
将其移至HAVING
子句(如错误状态)。
在小组之后发生。
having h.trx_date = MAX(h.trx_date)
答案 1 :(得分:0)
您需要使用专为此设计的HAVING
子句:
HAVING h.trx_date = MAX(h.trx_date)
然后将它放在GROUP BY
子句下面。