akretschmer
Datenbank-Guru
- Beiträge
- 10.206
Also, heute hatte ich ein Problem, was sehr stark verkürzt so aussah:
Die Aufgabe: jeden Wert val sooft wie anzahl duplizieren. Gut - das Problem war etwas größer, aber für hier reicht das als Einstand.
Erste Idee: easy, generate_series() nutzen:
Dieses "but it cannot be referenced from this part of the query" ist der Schlüssel: wann immer ihr bei PostgreSQL das als Fehler seht: lehnt Euch entspannt zurück und nehmt einen LATERAL JOIN:
Ich freu mich schon auf Eure Versuche, dies eleganter zu lösen ;-)
Code:
test=*# select * from foo;
val | anzahl
-----+--------
1 | 4
2 | 7
(2 rows)
Die Aufgabe: jeden Wert val sooft wie anzahl duplizieren. Gut - das Problem war etwas größer, aber für hier reicht das als Einstand.
Erste Idee: easy, generate_series() nutzen:
Code:
test=*# select * from foo cross join (select * from generate_series(1, foo.anzahl)) s;
ERROR: invalid reference to FROM-clause entry for table "foo"
LINE 1: ... foo cross join (select * from generate_series(1, foo.anzahl...
^
HINT: There is an entry for table "foo", but it cannot be referenced from this part of the query.
Time: 0,238 ms
Dieses "but it cannot be referenced from this part of the query" ist der Schlüssel: wann immer ihr bei PostgreSQL das als Fehler seht: lehnt Euch entspannt zurück und nehmt einen LATERAL JOIN:
Code:
test=*# select * from foo cross join lateral (select * from generate_series(1, foo.anzahl)) s;
val | anzahl | generate_series
-----+--------+-----------------
1 | 4 | 1
1 | 4 | 2
1 | 4 | 3
1 | 4 | 4
2 | 7 | 1
2 | 7 | 2
2 | 7 | 3
2 | 7 | 4
2 | 7 | 5
2 | 7 | 6
2 | 7 | 7
(11 rows)
Ich freu mich schon auf Eure Versuche, dies eleganter zu lösen ;-)