It sounds like something you could probably do in PostgreSQL with CTEs (common table expressions). I'm not 100% sure, but look into it.