Hello all,I've written a query which was working fine prior to me trying to add a sub-query. I'm trying to make sure I am getting the max disconnect date for each account that has been issued a refund. When I attempt to run the modified query, I receive the following error:Msg 147, Level 15, State 1, Line 43An 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.Here's the whole query:IF OBJECT_ID('TEMPDB..#TMP1A') IS NOT NULL DROP TABLE #TMP1ASELECT BC.ACCTCORP,BD.HOUSE,BD.CUST,BC.BATCH,BC.BADATE,BC.BATYPE,BD.AMOUNT,BD.ADJRSN,BC.OPR AS OPID,BC.CTLGRP,BD.POSTFLAGINTO #TMP1AFROM INFODDPFLORIDA.GGS.IDST_BATCH_CATALOG BC WITH(NOLOCK) INNER JOIN INFODDPFLORIDA.GGS.IDST_BATCH_DETAIL BD WITH(NOLOCK)ON BC.ACCTCORP=BD.ACCTCORP AND BC.BATCH=BD.BATCH AND BC.BADATE=BD.BADATEWHERE BC.CTLGRP = 'REFND' AND BC.BADATE BETWEEN '2013-10-01 00:00:00' AND getdate()SELECT DISTINCT A.ACCTCORP, RIGHT('00000' + CAST(A.ACCTCORP AS VARCHAR),5) + RIGHT('000000' + CAST(A.HOUSE AS VARCHAR),6) + RIGHT('00' + CAST(A.CUST AS VARCHAR),2) AS 'ACCOUNT_NUMBER', C.FNAME + ' ' + C.LNAME AS FULL_NAME, C.BDATE, A.BADATE AS BATCH_DATE, A.AMOUNT AS REF_AMOUNT, A.OPID, (C.CUR+C.C30+C.C60+C.C90+C.C120) AS TotalBalance, A.ADJRSN, --CO.BNUMB AS 'EQUIPMENT', BX.BNUMB AS EQUIP_SERIAL_NO, BX.PREVHOUSE, BX.LASTDATE, A.BATCH, A.CTLGRP, A.POSTFLAG FROM #TMP1A A (NOLOCK), INFODDPFlorida.ggs.IDST_CUSTOMER C (NOLOCK), INFODDPFlorida.ggs.IDST_CUST_OUTLET CO (NOLOCK), INFODDPFlorida.ggs.IDST_BOX_INVENTORY BX (NOLOCK)WHERE A.ACCTCORP = C.ACCTCORP AND A.HOUSE = C.HOUSE AND A.CUST = C.CUST AND C.ACCTCORP = CO.ACCTCORP AND C.HOUSE = CO.HOUSE AND C.CUST = CO.CUST AND CO.ACCTCORP = BX.ACCTCORP AND CO.HOUSE = BX.HOUSE AND CO.CUST = BX.CUST AND C.BDATE = (SELECT MAX(C.BDATE) AS DISCO_DTE FROM INFODDPFlorida.ggs.IDST_CUSTOMER AS B (NOLOCK) WHERE C.ACCTCORP = B.ACCTCORP AND C.HOUSE = B.HOUSE AND C.CUST = B.CUST HAVING C.BDATE < A.BADATE) AND C.STAT = '6'AND A.BADATE > C.BDATE GROUP BY A.ACCTCORP, A.HOUSE, A.CUST, C.FNAME, C.LNAME, C.BDATE, A.BADATE, A.AMOUNT, A.OPID, C.CUR, C.C30, C.C60, C.C90, C.C120, A.ADJRSN, BX.BNUMB, BX.PREVHOUSE, BX.LASTDATE, A.BATCH, A.CTLGRP, A.POSTFLAG
Any and all help is greatly appreciated! ThanksDamian