The result of this query has multiple transactionCodes. I want to group the transactionCodes only if applyToLineID = '0'. In other words, if the applyToLineID is something other than 0, the transaction codes should not be grouped. I think this can be done with HAVING statement, but I could not get it to work. Below you will find 2 pieces of code, the first piece is my original code, and the 2nd piece is the original code plus my attempt to perform the aforementioned grouping. 

Original Code:

```
SELECT 
ar.arlineitemid,
ar.siteid,
ar.transactioncode,
ar.description,
ar.amount,
ar.balance,
ar.applytolineid,
ar.posteddate,
TC.transactioncode,
TC.arlineitemid

FROM tswdata.dbo.t_arlineitem as AR     

left JOIN

(
SELECT

ar2.transactioncode,
ar2.arlineitemid

FROM tswdata.dbo.t_arlineitem as ar2    

WHERE  

ar2.SiteID = '101'
AND
(AR2.Transactioncode LIKE 'A%'  And
AR2.Transactioncode NOT LIKE 'AS%' And
AR2.Transactioncode NOT LIKE 'AF%' And
AR2.Transactioncode NOT LIKE 'AX%')
) TC

ON
ar.applytolineid = TC.arlineitemid

WHERE  

ar.SiteID = '101'
AND
AR.Transactioncode <> 'A18'

```

Code where I tried to perform the conditional grouping:

```
SELECT 
ar.arlineitemid,
ar.siteid,
ar.transactioncode,
ar.description,
ar.amount,
ar.balance,
ar.applytolineid,
ar.posteddate,
TC.transactioncode,
TC.arlineitemid

FROM tswdata.dbo.t_arlineitem as AR     

left JOIN

(
SELECT

ar2.transactioncode,
ar2.arlineitemid

FROM tswdata.dbo.t_arlineitem as ar2    

WHERE  

ar2.SiteID = '101'
AND
(AR2.Transactioncode LIKE 'A%'  And
AR2.Transactioncode NOT LIKE 'AS%' And
AR2.Transactioncode NOT LIKE 'AF%' And
AR2.Transactioncode NOT LIKE 'AX%')
) TC

ON
ar.applytolineid = TC.arlineitemid

WHERE  

ar.SiteID = '101'
AND
AR.Transactioncode <> 'A18'

GROUP BY 
ar.transactioncode,

HAVING
ar.ApplyTolineId = '0'

```