You can find here sources of an extension to QGIS that introduces "virtual layers" which are database views over existing QGIS (vector) layers. These layers can be built by the use of the powerful SQL ...