SQL queries to Excel are limited in their functionality. You will not be allowed to do CTEs or similar things there. They only support simple queries.
Instead, read the entire table and apply the appropriate filtering in the flow logic, by either using a .NET script, or simply native Excel actions.
Or, alternatively, push the data to an actual database first, and then do proper SQL queries to it.
-------------------------------------------------------------------------
If I have answered your question, please mark it as the preferred solution. If you like my response, please give it a Thumbs Up.
I also provide paid consultancy and development services using Power Automate. If you're interested, DM me and we can discuss it.