select sum group by - dołączanie 0 (null) wartości

0

Witam
Mam taką zagwozdkę,otóż mam taką baze danych prostą:

create table category(
	id serial primary key not null,
	category varchar(100) unique not null
);

create table payment_method(
	id serial primary key not null,
	payment_method varchar(100) unique not null
);

create table payee(
	id serial primary key not null,
	payee varchar(200) unique not null
);


create table expense(
	id serial primary key not null,
	expense_date date not null,
	ammount decimal(10,2),
	comment text,
	category_id integer not null,
	payment_method_id integer not null,
	payee_id integer not null,
	constraint fk_category foreign key(category_id) references category(id),
	constraint fk_payee foreign key(payee_id) references payee(id),
	check (ammount>0)
);

 

Chcę zsumować wszystkie wydatki po kategoriach i wybrać wartość 0 jeśi nie było wydatków w danej kategorii. W przypadku gdy biorę pod uwagę cały zakres nie ma problemu,

select c.category,coalesce(sum(e.ammount),0) from category c
left join expense e on c.id = e.category_id
group by c.category;
 

I śmiga,problem jest wtedy kiedy bym chciał wybrac po datach wydatków...
Jedyne co wymyśliłem to:

select category,(select sum(e.ammount) from expense e where e.category_id = category.id and  e.expense_date between '2016-01-01' and '2016-05-01')  from category;
 

Ale to nie jest specjalnie optymalne,poradzi ktoś coś innego?

1

Dodaj warunek na daty w joinie:

select 
    c.category
    ,coalesce(sum(e.ammount),0) 
from 
    category c
    left join expense e on c.id = e.category_id  and  e.expense_date between '2016-01-01' and '2016-05-01'
group by 
    c.category;
0

Faktycznie działa dzięki :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1