Zeilen/Spalten -Tausch

Ludwigmller

SQL-Guru
Beiträge
168
Bin mir nicht sicher ob der Titel richtig gewählt ist, aber zumindest zum Teil trifft es auf mein Vorhaben zu...
Hier eine Tabelle mit Beispieldaten:

Code:
CREATE TABLE test.test_1 (
    test_id integer NOT NULL,
    typ integer,
    anzahl integer,
    kategorie integer,
    unterkategorie integer,
    artikel_id integer
);
INSERT INTO test.test_1 VALUES (1, 1, 10, 1, 1, 1);
INSERT INTO test.test_1 VALUES (2, 2, 8, 1, 1, 1);
INSERT INTO test.test_1 VALUES (3, 3, 2, 1, 1, 1);
INSERT INTO test.test_1 VALUES (4, 1, 5, 1, 1, 2);
INSERT INTO test.test_1 VALUES (5, 2, 1, 1, 1, 2);
INSERT INTO test.test_1 VALUES (6, 1, 20, 1, 2, 3);
INSERT INTO test.test_1 VALUES (7, 2, 10, 1, 2, 3);
INSERT INTO test.test_1 VALUES (8, 1, 5, 2, 1, 4);
INSERT INTO test.test_1 VALUES (9, 2, 3, 2, 1, 4);
INSERT INTO test.test_1 VALUES (10, 3, 2, 2, 1, 4);
INSERT INTO test.test_1 VALUES (11, 1, 50, 3, 1, 5);

Ich möchte eine Abfrage, die mir ein Ergebnis wie folgt liefert:
Code:
artikel_id | typ1 | typ2 | typ3 | total
1          | 10   | 8    | 2    | 20
2          | 5    | 1    | 0    | 6
.....
Letztendlich soll jeder Typ in % von der Gesamtsumme angegeben werden.

Eine weitere Abfrage soll ebenfalls typ1, typ2, typ3 und total ausgeben, jedoch nicht je artikel_id, sondern nach kategorie.

Wie mach ich das am besten? Mein Ansatz wäre etwas wie folgt. Sicher nicht gut und funktioniert auch nicht ganz...
Code:
with cte as(
   select distinct
       t.artikel_id ,
       (SELECT anzahl FROM test.test_1 as t1 WHERE t1.typ =1 and t1.artikel_id = t.artikel_id) as typ1,
       (SELECT anzahl FROM test.test_1 as t1 WHERE t1.typ =2 and t1.artikel_id = t.artikel_id) as typ2,
       (SELECT anzahl FROM test.test_1 as t1 WHERE t1.typ =3 and t1.artikel_id = t.artikel_id) as typ3
   FROM
       test.test_1 as t
)

select
   typ1, typ2, typ3,
   typ1+typ2+typ3 as total
from cte
 
Werbung:
Warum ist denn typ1 für artikel_id 1 nur 10? Das sind doch zwei Datensätze mit artikel_id = 1 und typ = 1 - ich hätte da 20 (also die Summe erwartet)

Wenn das nur ein Tippfehler ist, dann geht das recht einfach mit FILTER

Code:
select artikel_id,
       sum(anzahl) filter (where typ = 1) as typ1,
       sum(anzahl) filter (where typ = 2) as typ2,
       sum(anzahl) filter (where typ = 3) as typ3,
       sum(anzahl) as total
from test_1
group by artikel_id
order by artikel_id;
 
Zurück
Oben