gpt4 book ai didi

mysql按照规模聚合

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

我需要从数据库中选择数据,并根据规模进行聚合。当我有下面的数据时,我想聚合 col1 中从一到三、从四到六等范围内的列 col2 的数据。

col1 |  col2
-----+----
1 | 34
2 | 43
3 | 75
4 | 23
5 | 62
6 | 33
... | ...

结果会是这样的:

| SUM(col2)
+----
152 - for values from 1 to 3
118 - for values from 4 to 6
... ...

我不知道如何编写一个可以返回此数据的 SQL select。感谢您的回答,并对我的英语表示抱歉。

最佳答案

CREATE TABLE t (col1 integer, col2 integer);
INSERT INTO t VALUES (1,34),(2,43),(3,75),(4,23),(5,62),(6,33);

SELECT ceil(col1/3) AS grp, min(col1) AS col1_from,
max(col1) AS col1_till, sum(col2)
FROM t
GROUP BY ceil(col1/3);

同时在 SQL Fiddle .

关于mysql按照规模聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11334370/

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