Eine kleine Anfrage, die aber ein kniffeliges Problem darstellt.
Ausgangsbasis Tabelle "mitarbeiter"
Firma Name Typ
------------------
IBM Fritz A
IBM Max A
IBM Josef B
Sun Otto B
Ich will nun alle Personen aller Firma des Typs A, aber wenns keine
gibt, dann alle Personen des Typs B. Also ugs. "entweder A oder B." B
ist der Fallback.
Die Lösung wäre also (Der Max fällt raus):
Firma Name Typ
------------------
IBM Fritz A
IBM Max A
Sun Otto B
Wir haben das schon so gelöst, indem wir uns den Vorteil zu Nutzen
gemacht haben, dass A<B:
select * from mitarbeiter where (firma, typ) in
(select Firma, Min(Typ) from mitarbeiter group by Firma)
select distinct b.* from mitarbeiter a
join mitarbeiter b on b.firma = a.firma and b.typ =
(select Min(c.Typ) from mitarbeiter c where c.firma = a.firma)
Aber lieber wärs mir, wenn ich konkret angeben könnte, welcher Wert
bevorzugt wird und welcher als Fallback dient, weil in Wirklichkeit
sinds nicht A oder B, sondern andere Werte. Gut, die Prüfung, welcher
größer ist und welcher kleiner ist, ist jetzt nicht aufwändig und dann
entsprehcend MIN oder MAX einbauen.
FAlls aber jeamnd grad adhoc eine bessere Lösung weiss, nehm ich sie
gerne. Aber bitte nicht überanstrengen, ich schaffs auch mit einer der
obigen Lösungen. Ich lern aber gerne dazu :)
lg und schönes Wochenende!
gehst sicher noch schöner, aber wie wäre es damit?
test=*# select * from mitarbeiter ;
firma | name | typ
-------+-------+-----
IBM | Fritz | A
IBM | Max | A
IBM | Josef | B
Sun | Otto | B
(4 rows)
test=*# select firma, name, typ from mitarbeiter where typ='A' union all
select firma, name, typ from mitarbeiter where typ != 'A' and firma not
in (select firma from mitarbeiter where typ = 'A');
firma | name | typ
-------+-------+-----
IBM | Fritz | A
IBM | Max | A
Sun | Otto | B
(3 rows)
Andreas
--
Andreas Kretschmer
Linux - weil ich es mir wert bin!
GnuPG-ID 0x3FFF606C http://wwwkeys.de.pgp.net
>
>gehst sicher noch schöner, aber wie wäre es damit?
>
>test=*# select firma, name, typ from mitarbeiter where typ='A' union all
>select firma, name, typ from mitarbeiter where typ != 'A' and firma not
>in (select firma from mitarbeiter where typ = 'A');
> firma | name | typ
>-------+-------+-----
> IBM | Fritz | A
> IBM | Max | A
> Sun | Otto | B
>(3 rows)
Danke Andreas! Super! Eigentlich liest sich das im Nachhinein eh viel
logischer und einfacher. :)
lg Michael