Я пытаюсь рассчитать общий объем продаж за каждый час по категориям продуктов питания.
Это имеет смысл, но не имеет смысла включать shopid
в результаты.
Чтобы сделать это, вам нужно сгенерировать строки - все часы и категории продуктов. Затем введите фактические результаты, используя left join
:
select c.category. g.hour, coalesce(sum(s.amount), 0)
from generate_series(6, 22) g(hour) cross join
(select distinct category from sales) c left join
sales s
on s.hour = g.hour and s.category = c.category
group by c.category, g.hour
order by c.category, g.hour;
Если вам нужны результаты по магазинам / категориям / часам, вы можете использовать ту же идею:
select sh.shopid, c.category. g.hour,
coalesce(sum(s.amount), 0)
from generate_series(6, 22) g(hour) cross join
(select distinct category from sales) c cross join
(select distinct shopid from sales) sh left join
sales s
on s.shopid = sh.shopid and
s.hour = g.hour and
s.category = c.category
group by sh.shopid, c.category, g.hour
order by sh.shopid, c.category, g.hour;