Hi,
(1) Next time when you use code then please use the button for code so the text will be formatted well. I edited your message and did it for you this time :-)
(2) In order to text a solution we need a table and data. Please provide queries to CREATE the table and INSERT some sample data. Next you need to present the expected result set according to the sample data, so we will be able to discuss it without the need to read minds or play "the guessing game"
(3) In the meantime, In general, you can wrap your code inside a CTE and aggregate the data in the external query
Read more here about using CTE.
Finally, there is something not clear in your request. It is simple to aggregate the values by the columns name,ref,a.date and use SUM function to get the aggregated value for the final isnew column, but not cl,ear to me how you chose the value of the category if you have for example two or more different categories
Please explain the logic to get the final result and don't forget to provide the missing information as mentioned above