In my PostgreSQL database I have the following schema:
CREATE TABLE clients (
id integer NOT NULL,
name character varying(255)
);
CREATE TABLE services (
id integer NOT NULL,
name character varying(255) NOT NULL
);
CREATE TABLE client_services (
id integer NOT NULL,
client_id integer NOT NULL,
service_id integer NOT NULL
);
INSERT INTO clients(id, name)
VALUES (1, 'Client 1'),
(2, 'Client 2');
INSERT INTO services(id, name)
VALUES (1, 'Service 1'),
(2, 'Service 2');
INSERT INTO client_services(id, client_id, service_id)
VALUES (1, 1, 1),
(2, 1, 2),
(3, 2, 2);
and I have the following query:
SELECT DISTINCT
c.name,
COUNT(cs.id) FILTER(WHERE s.name = 'Service 1') AS "Service 1",
COUNT(cs.id) FILTER(WHERE s.name = 'Service 2') AS "Service 2"
FROM
clients c
INNER JOIN
client_services cs ON cs.client_id = c.id
INNER JOIN
services s ON s.id = cs.service_id
GROUP BY
c.name;
which returns this:
| name | Service 1 | Service 2 |
| -------- | --------- | --------- |
| Client 1 | 1 | 1 |
| Client 2 | 0 | 1 |
Problem is that if I decide to add another service to services
table I will need to update my query. Is there any way to make that part of the query dynamic:
COUNT(cs.id) FILTER(WHERE s.name = 'Service 1') AS "Service 1",
COUNT(cs.id) FILTER(WHERE s.name = 'Service 2') AS "Service 2"
EDIT:
I forgot to add link do sql fiddle: