Error Code : 1248 Every derived table must have its own alias in MySQL
You need to mention an alias for all your inline views / derived tables in MySQL, even when they are nested. In your code you are using a derived table inside another derived table but you seem to have forgotten to mention an alias for your inner derived table. Put an alias before the 4th line from the bottom which is GROUP BY REF_ID. Put an alias before this group by clause and you will be fine.