2017-10-04 3 views
3

Bitte helfen Sie uns kommen: Ich habe folgende Tabelle Umsatz:verbessern „abgeschlossen“ mit Abfrage Abfrage postgresql

customer material week value 
customer1 material1 w1  100 
customer1 material1 w2  200 
customer1 material1 w4  300 
customer1 material2 w4  200 

Und Tabelle Wochen

week 
w1 
w2 
w3 
w4 

Ich brauche Abfrage zu schreiben, die Tabelle zurückgibt mit " vervollständigte Daten ". Ergebnistabelle muss sein:

customer material week value 
customer1 material1 w1  100 
customer1 material1 w2  200 
customer1 material1 w3  0 
customer1 material1 w4  300 
customer1 material2 w1  0 
customer1 material2 w2  0 
customer1 material2 w3  0 
customer1 material2 w4  200 

Ich schreibe diese Abfrage, aber ich denke, das ist nicht optimal ist.

select 
    dict.customer, 
    dict.material, 
    weeks.week, 
    coalesce(sales.value, 0) 
from 
    (select distinct 
     customer, 
     material 
    from 
     sales) dict 
cross join 
     weeks 
left join 
    sales on dict.customer = sales.customer and 
      dict.material = sales.material and 
      weeks.week = sales.week 

Script für Tisch Initialisierungen:

CREATE TABLE public.sales 
(
    customer character varying(10), 
    material character varying(18), 
    week character varying(3), 
    value numeric 
); 

CREATE TABLE public.weeks 
(
    week character varying(3) 
); 


insert into public.sales (customer, material, week, value) 
values ('customer1', 'material1', 'w1', 100), 
    ('customer1', 'material1', 'w2', 200), 
    ('customer1', 'material1', 'w4', 300), 
    ('customer1', 'material2', 'w4', 200); 

insert into public.weeks (week) 
values ('w1'), ('w2'), ('w3'), ('w4'); 

Danke.

Antwort

1
select 
    customer, 
    material, 
    week, 
    coalesce(sum(value), 0) as value 
from 
    sales 
    right join (
     (
      select distinct customer, material 
      from sales 
     ) s 
     cross join 
     weeks 
    ) s using (customer, material, week) 
group by 1,2,3 
; 
customer | material | week | value 
-----------+-----------+------+------- 
customer1 | material1 | w1 | 100 
customer1 | material1 | w2 | 200 
customer1 | material1 | w3 |  0 
customer1 | material1 | w4 | 300 
customer1 | material2 | w1 |  0 
customer1 | material2 | w2 |  0 
customer1 | material2 | w3 |  0 
customer1 | material2 | w4 | 200 
+0

es ist nicht das, was ich brauche –

+0

@NikitaBannikov –

+0

Ok Fest, es ist wahr, aber ich schlug vor, diese Abfrage in meiner Frage und ich denke, es ist nicht optimal, weil Verkaufstisch groß sein (über 5 Millionen) und cartesianischen Produkt in Dieser Fall wird sehr groß sein. –