Hi.
Compiling such sql is almost impossible. Several nested SELECTs would have to be inserted. You cannot use more than one SELECT in Prestashop's SQL manager, and you cannot use IF functions, etc.
The solution for you is php and the use of Prestashop functions.
Can you please tell me what programming knowledge you have with Prestashop?
Should the output be a CSV file?