PostgreSQL查询中的动态列

时间:2019-03-25 07:20:10

标签: sql postgresql pivot

在我的PostgreSQL数据库中,我具有以下架构:

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

,我有以下查询:

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; 

返回以下内容:

| name     | Service 1 | Service 2 |
| -------- | --------- | --------- |
| Client 1 | 1         | 1         |
| Client 2 | 0         | 1         |

问题是,如果我决定向services表添加另一个服务,则需要更新查询。有什么方法可以使查询的这一部分动态化:

COUNT(cs.id) FILTER(WHERE s.name = 'Service 1') AS "Service 1",
COUNT(cs.id) FILTER(WHERE s.name = 'Service 2') AS "Service 2"

编辑:

我忘了添加链接做sql小提琴:

https://www.db-fiddle.com/f/mhcs7UBpW93fHoYqadNZMx/1

0 个答案:

没有答案