new*_*irl 5 sql postgresql postgresql-9.3
创建临时表
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
------+-------+------
9 | 3 | 100
10 | 3 | 89
(2 rows)
Run Code Online (Sandbox Code Playgroud)
题
如何返回每列的总数?
想要的结果:
zoom | point | size
------+-------+------
9 | 3 | 100
10 | 3 | 89
------+-------+------
Total | 6 | 189
Run Code Online (Sandbox Code Playgroud)
模拟汇总的方法是简单地运行执行汇总的第二个查询。但是,列中的所有值必须具有相同的数据类型。当您想显示标签时,'Total'您还需要将zoom基本查询中的数字转换为文本:
但由于您想按实际缩放值排序,您还需要在结果中保留整数值。
在sort_order确保必要从工会的第一部分实际上行留“顶部”
select zoom, point, size
FROM (
SELECT zoom::text as zoom,
zoom as zoom_value,
count(*) AS point,
SUM(size) AS size,
1 as sort_order
FROM total
GROUP BY zoom
UNION ALL
SELECT 'Total',
null,
count(*) AS point,
SUM(size) AS size,
2 as sort_order
FROM total
) t
order by sort_order, zoom_value;
Run Code Online (Sandbox Code Playgroud)
这将返回:
select zoom, point, size
FROM (
SELECT zoom::text as zoom,
zoom as zoom_value,
count(*) AS point,
SUM(size) AS size,
1 as sort_order
FROM total
GROUP BY zoom
UNION ALL
SELECT 'Total',
null,
count(*) AS point,
SUM(size) AS size,
2 as sort_order
FROM total
) t
order by sort_order, zoom_value;
Run Code Online (Sandbox Code Playgroud)
使用最新的 Postgres 版本,您可以执行以下操作:
SELECT case when grouping(zoom) = 1 then 'Total' else zoom::text end,
count(*) AS point,
SUM(size) AS size
FROM total
GROUP BY rollup (zoom)
order by zoom;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3639 次 |
| 最近记录: |