gpt4 book ai didi

sql - 我怎样才能得到每列的总和?

转载 作者:行者123 更新时间:2023-11-29 11:42:44 24 4
gpt4 key购买 nike

创建临时表

CREATE TEMP TABLE total(
gid SERIAL,
zoom smallint NOT NULL,
point integer NOT NULL,
size integer NOT NULL
);

插入数据

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

计数点数,根据 ZOOM 添加 SIZE

SELECT zoom,
count(*) AS point,
SUM(size) AS size
FROM total
GROUP BY zoom
ORDER BY zoom;

结果:

 zoom | point | size 
------+-------+------
9 | 3 | 100
10 | 3 | 89
(2 rows)

问题

如何返回每列的总数?

想要的结果:

 zoom | point | size 
------+-------+------
9 | 3 | 100
10 | 3 | 89
------+-------+------
Total | 6 | 189

最佳答案

模拟汇总的方法是简单地运行第二个执行汇总的查询。但是,列中的所有值必须具有相同的数据类型。当您想要显示标签 '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;

返回:

zoom  | point | size
------+-------+-----
9 | 3 | 100
10 | 3 | 89
Total | 6 | 189

使用最新的 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;

关于sql - 我怎样才能得到每列的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39986009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com