Trickkiste: Multiplikations-Aggregation

akretschmer

Datenbank-Guru
Beiträge
10.324
Irgendwer fragte, warum es sum() und avg() gibt, aber kein mul() als Aggregation.

Was für eine Frage! Do-it-yourself!

Code:
test=*# create table demo (cat int, val int);
CREATE TABLE
Time: 1,105 ms
test=*# copy demo from stdin;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 1  2
>> 1  4
>> 1  6
>> 2  4
>> 2  3
>> 2  2
>> 3  7
>> 3  8
>> 3  10
>> \.
Time: 23195,573 ms
--
-- nun haben wir erst einmal eine Tabelle. Die Spalte val soll multipliziert werden, gruppiert nach cat
-- wir bauen usn eine mul() - Aggregation:
--
test=*# create or replace function mul(int,int) returns int as $$ select $1 * $2;$$ language sql;
CREATE FUNCTION
Time: 0,350 ms
test=*# create aggregate mul (int) (sfunc = mul, stype = int, initcond = 1);
CREATE AGGREGATE
Time: 0,624 ms
--
-- diese besteht aus einer Funktion, hier mul(int, int), und einer Aggregation, die diese Funktion nutzt
-- nun die Anwendung:
--
test=*# select cat, mul(val) from demo group by cat;
 cat | mul
-----+-----
  1 |  48
  3 | 560
  2 |  24
(3 rows)


Cool, oder?
 
Werbung:
Werbung:
Zurück
Oben