Seite 1 von 1

Abfrage soll aus "join" neue spalten erzeugen

Verfasst: Mo, 07.12.2009 23:16
von 2morpheus
Moin,
mal wieder eine Anfängerfrage:
ich habe zwei Tabellen:
Tabelle 1

Code: Alles auswählen

ID | c1 | c2 |
2    xx    yy
3    xy    yz
4    yd    yf
Tabelle 2

Code: Alles auswählen

IDo  |  titel | content
2        t1     ct12
2        t2     ct22
2        t3     ct32 
3        t1     ct13
3        t3     ct33
4        t2     ct24
4        t3     ct34
und daraus soll entstehen:

Code: Alles auswählen

ID | c1 | c2 |  t1  |  t2  |  t3
2    xx    yy   ct12  ct22  ct32
3    xy    yz   ct13        ct33
4    yd    yf         ct24  ct34
Das sind benutzerdefinierte Felder (Tabelle 2) zu Tabelle 1, die auf diese Weise abgelegt werden. Jedes Feld bezieht sich auf die ID des Datensatzes in der ersten Tabelle.
Wäre toll wenn ihr mir mit einem Hinweis helfen könntet.

In Postgresql könnte es so aussehen:

Code: Alles auswählen

select t1.*, array_to_string(array_agg(case when t2.titel = 't1' then t2.content else null end),',') as t1, array_to_string(array_agg(case when t2.titel='t2' then t2.content else null end),',') as t2, array_to_string(array_agg(case when t2.titel = 't3' then t2.content else null end),',') as t3 from t1 left join t2 on t1.id=t2.ido group by 1,2,3;
 id | c1 | c2 |  t1  |  t2  |  t3
----+----+----+------+------+------
  2 | xx | yy | ct12 | ct22 | ct32
  3 | xy | yz | ct13 |      | ct33
  4 | yd | yf |      | ct24 | ct34
(3 Zeilen)

Viele Grüße

Christian

Re: Abfrage soll aus "join" neue spalten erzeugen

Verfasst: Do, 10.12.2009 20:25
von Barlee
Hallo 2morpheus,

ist gar nicht so schwierig. Probiere einmal so:

Code: Alles auswählen

SELECT "a".*, "b"."t1", "c"."t2", "d"."t3" FROM "Tabelle1" "a"
LEFT JOIN  (SELECT "IDo", "content" AS "t1" FROM "Tabelle2" WHERE "titel" = 't1') "b" ON "a"."ID" = "b"."IDo"
LEFT JOIN  (SELECT "IDo", "content" AS "t2" FROM "Tabelle2" WHERE "titel" = 't2') "c" ON "a"."ID" = "c"."IDo"
LEFT JOIN  (SELECT "IDo", "content" AS "t3" FROM "Tabelle2" WHERE "titel" = 't3') "d" ON "a"."ID" = "d"."IDo"
!SQL direkt ausführen aktivieren"

Gruß Barlee