CREATE TABLE dep
(
id integer NOT NULL,
city text NOT NULL,
name text NOT NULL,
CONSTRAINT dep_pk PRIMARY KEY (id)
);
-- продукты
CREATE TABLE prod
(
id integer NOT NULL,
price integer NOT NULL,
name text NOT NULL,
CONSTRAINT prod_pk PRIMARY KEY (id)
);
-- продажи
CREATE TABLE sales
(
time timestamp NOT NULL,
dep_id integer NOT NULL,
prod_id integer NOT NULL,
cost numeric(10, 2) NOT NULL,
CONSTRAINT sales_fk1 FOREIGN KEY (dep_id) REFERENCES dep (id),
CONSTRAINT sales_fk2 FOREIGN KEY (prod_id) REFERENCES prod (id)
);
commit;
select EXTRACT(YEAR FROM time) AS YEAR, EXTRACT(month FROM time) AS month,SUM(cost) as сумма_продаж
FROM
dep
INNER JOIN prod ON prod.id = dep.id
INNER JOIN sales ON prod.id = sales.prod_id
WHERE time >= '2018-01-01 00:00:00'
AND city = 'town1'
GROUP BY year, month
select EXTRACT(YEAR FROM time) AS year,
sum(cost) filter(where EXTRACT('month' FROM time) = 1) as jan,
sum(cost) filter(where EXTRACT('month' FROM time) = 2) as feb,
...
sum(cost) filter(where EXTRACT('month' FROM time) = 12) as dec
from tablename
where ...
group by 1
order by 1