Revision def2fecc-91ab-471f-aebe-0e9b084e021b - Stack Overflow
CREATE FUNCTION samplefunc()
RETURNS TABLE(ntested int, rawscore int, growth int) AS
$func$
SELECT count(DISTINCT student_id) -- AS NTested
,avg(raw_score)::int -- AS RawScore
,avg(growth)::int -- AS Growth
FROM reports_results
WHERE test_type_id = 1
AND test_id = '201403MAME04'
$func$ LANGUAGE sql;
- The clause to return a table is [**`RETURNS TABLE`**][1]
Also:
- `avg(growth)` would result in a type mismatch with the declared return type `int`. You need to cast that, too.
Better yet: return [`numeric` or a floating point number][2] to preserve fractional digits in your avg numbers.
- column aliases are only visible inside the function. If you are not going to reference them *inside* the function, they are just documentation.
- What's with the capitalization? Unquoted identifiers are cast to lower case in Postgres automatically.
[1]: http://www.postgresql.org/docs/current/interactive/sql-createfunction.html
[2]: http://www.postgresql.org/docs/current/interactive/datatype-numeric.html