I need to write a query that returns both aggregate and non-aggregate data from a table.
The example below should help clarify what I'm trying to do. I have the following (simplified) tables below:
CREATE TABLE course_group_def ( id PRIMARY SERIAL KEY, name TEXT NOT NULL ); CREATE TABLE student ( id PRIMARY SERIAL KEY, grp_id INTEGER REFERENCES course_group_def(id) ON UPDATE CASCADE, name TEXT NOT NULL, weight float NOT NULL, height float NOT NULL );
For argument, suppose that each student belongs to one and only a group of courses. I want to write a query that will return a result set as follows:
student.name, student.weight, weight_apgaw, weight_apgh
Where:
weight_apgaw: - the weight of an individual student, expressed as a percentage of the average weight of the group of courses to which he / she belongs.
weight_apgh: this is the weight of the individual student, expressed as a percentage of the average height of the group of courses to which he / she belongs
I have no idea (well, some idea) on how to write such a request. My approach would be to write two queries and somehow search between the two tables, but this approach seems at best pointless and inefficient.
Can anyone suggest how I can write such an SQL function correctly ?. Ideally, this should be db agnostic. However, I use PostgreSQL 8.4, so if I need to choose between SQL options, this takes precedence.