2017-10-04 12 views
3

に参加し、「完了」を改善するクエリで私を助けてください: は、私は、テーブルの販売を次ていますは、クエリのpostgresql

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

とテーブル週間

week 
w1 
w2 
w3 
w4 

を私はテーブルを返すクエリを記述する必要があります」完成したデータ "である。 結果テーブルでなければなりません:

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 

私はこのクエリを書くが、私は、これは最適ではないと思います。テーブルの初期化のための

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 

スクリプト:

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'); 

ありがとうございました。

答えて

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

それは私が –

+0

@NikitaBannikovが固定に必要なものではありません –

+0

[OK]を、それは本当だが、私は私の質問にこのクエリを示唆したと私は売上テーブルは大きなものとなりますので、それは最適ではないと思います(500万)と直積でこの場合は非常に大きくなります。 –