我有一张如下表格
table1
---------
x y z total average
========================
1 2 3
2 3 4
3 4 5
这里我只需要在前端对应列中选择列 需要一个总和平均 例如,如果我选择前端的x,y,total,average列 我需要一个如下所示的输出
x y total avg
1 2 3 1.5
2 3 5 2.5
3 4 7 3.5
这里使用refcursor with dynamicsql
create or replace function sample_refcursor(i_column in varchar) returns refcursor as
$$
declare
c1 refcursor;
begin
drop table if exists temp_t;
create temp table temp_t as select x as A,y as B,z as C,total as tot,avg as average from table1;
open c1 for execute('select ' ||i_column|| ' from temp_t group by ' ||i_column);
return c1;
close c1;
end;
$$ language plpgsql
答案 0 :(得分:1)
您可以尝试:SELECT x,y, x+y AS total, (x+y)/2 AS average FROM Table;
答案 1 :(得分:1)
SELECT x, y, x+y AS tot, (x+y)/2 AS Avg From TableName
我按照你的第二张表,你没有使用z。
使用以下代码
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = 'SELECT x, y, x+y AS tot, (x+y)/2 AS Avg From TableName';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>