Abfrage von Gesamtmenge und Teilmenge in einer Abfrage

Hallo Wissende,

ich habe eine Tabelle mit den Feldern: ID, Type, datum, art. Aufgabe ist es, die Gesamtanzahl sowie die anzahl einer bestimmten art je type darzustellen. ist dies in einem Query möglich? Mein Anzatz ist bisher:
select


(
select count ID)
from Tabelle
where art = ‘irgendwas’
AND (“DATE”>=TO_DATE (‘01-10-2012 00:00:01’, ‘DD-MM-YYYY HH24:MI:SS’)
AND “DATE”<TO_DATE (‘01-01-2013 00:00:00’, ‘DD-MM-YYYY HH24:MI:SS’))

),
(select count ID)
from tabelle
where
(“DATE”>=TO_DATE (‘01-10-2012 00:00:01’, ‘DD-MM-YYYY HH24:MI:SS’)
DATE"<TO_DATE (‘01-01-2013 00:00:00’, ‘DD-MM-YYYY HH24:MI:SS’))

)

from tabelle

Dies liefert mir je ID einen Datensatz mit der gesamtzahl und auch der Anzahl der gewünschten Art. Ich müsste das aber nun noch pro typ haben, da scheitere ich. Hat da jemand eine Idee?

Vielen Dank im Voraus.

Sowas geht mit window-functions.

test=*# select * from wurbo;
 id | type
----+------
  1 |    1
  2 |    1
  3 |    1
  4 |    2
  5 |    3
  6 |    3
  7 |    3
  8 |    3
  9 |    3
 10 |    3
 11 |    4
 12 |    4
 13 |    4
 14 |    5
 15 |    5
 16 |    6
(16 rows)

test=*# select distinct type, count(*) over (partition by type), count(*) over() from wurbo order by 1;
 type | count | count
------+-------+-------
    1 |     3 |    16
    2 |     1 |    16
    3 |     6 |    16
    4 |     3 |    16
    5 |     2 |    16
    6 |     1 |    16
(6 rows)

so in der art …


Andreas

Hallo Andreas,

erst einmal danke, dass Du Dich mit meiner Problematik beschäftigt hast.
Das Resultat nährt sich dem gesuchten, allerdings nicht detailliert genug. Ich benötige aus der Gesamtmenge die Anzahl je Typ, und daneben die Anzahl einer bestimmten Art innerhalb des Types. das Resultat sollte dann ungefähr so aussehen (Deine Beispieldaten verwendet.
id | type art
----±-----
1 | 1 1
2 | 1 2
3 | 1 1
4 | 2 1
5 | 3 2
6 | 3 1
7 | 3 1
8 | 3 2
9 | 3 1
10 | 3 1
11 | 4 1
12 | 4 2
13 | 4 2
14 | 5 2
15 | 5 1
16 | 6 1

gewünschtes Ergebnis:

type gesamt art=1

1 3 2
2 1 1
3 6 4
4 3 1
5 2 1
6 1 1

Mein (neuer) Ansatz wäre:
select distinct type, count() over (partition by type )as a1,count() over (partition by type WHERE art = 1 )as a2
nur dass eben “where” im over partition nicht geht…