小编new*_*irl的帖子

在PostgreSQL中动态生成列

我已经看到有一些类似的问题已经退出,但是我还不了解如何自己编写代码。请记住,我只是该领域的初学者。

基本上我想像这样旋转表:

zoom |    day     | point         zoom | 2015-10-01 |  2015-10-02 | ......
------+-----------+-------  ---> ------+------------+-------------+
   1 | 2015-10-01 |   201            1 |    201     |     685     |
   2 | 2015-10-01 |    43            2 |     43     |     346     | 
   3 | 2015-10-01 |    80            3 |     80     |     534     | 
   4 | 2015-10-01 |   324            4 |    324     |     786     | 
   5 | 2015-10-01 |    25            5 |     25     |     685     |
   1 | 2015-10-02 |   685 
   2 | 2015-10-02 …
Run Code Online (Sandbox Code Playgroud)

postgresql dynamic-sql crosstab plpgsql postgresql-9.3

7
推荐指数
1
解决办法
7692
查看次数

如何获得每列的总和?

创建临时表

CREATE TEMP TABLE total(
gid SERIAL,
zoom smallint NOT NULL,
point integer NOT NULL,
size integer NOT NULL
);
Run Code Online (Sandbox Code Playgroud)

插入数据

INSERT INTO total(zoom, point, size) VALUES(9,51,21);
INSERT INTO total(zoom, point, size) VALUES(9,75,45);
INSERT INTO total(zoom, point, size) VALUES(9,74,34);
INSERT INTO total(zoom, point, size) VALUES(10,75,4);
INSERT INTO total(zoom, point, size) VALUES(10,72,63);
INSERT INTO total(zoom, point, size) VALUES(10,85,22);
Run Code Online (Sandbox Code Playgroud)

计数点,根据缩放增加尺寸

SELECT zoom,
       count(*) AS point,
       SUM(size) AS size
FROM total
GROUP BY zoom
ORDER BY zoom;
Run Code Online (Sandbox Code Playgroud)

结果:

 zoom | point | size …
Run Code Online (Sandbox Code Playgroud)

sql postgresql postgresql-9.3

5
推荐指数
1
解决办法
3639
查看次数