gpt4 book ai didi

sql - 如何计算sql中聚合中的数字?

转载 作者:行者123 更新时间:2023-11-29 12:52:23 25 4
gpt4 key购买 nike

所以我想聚合共享相同位置的点组,然后计算属于该点的每个类的数量。

我的聚合查询如下:

create table mytable2 as
select count(*) as rows, location, string_agg(distinct class, ', ' order by class)
from mytable
group by location

这个结果给了我一行

 (16, 'Wakanda', 'warrior priest tank')

我如何聚合它以代替显示

(16, 'Wakanda', '10 warrior 5 priest 1 tank')

最佳答案

示例数据:

create table mytable(location text, class text);
insert into mytable values
('Wakanda', 'warrior'),
('Wakanda', 'warrior'),
('Wakanda', 'priest'),
('Wakanda', 'tank'),
('Wakanda', 'tank'),
('Wakanda', 'warrior');

使用grouping sets.您可以轻松获得漂亮的表格输出:

select location, class, count(*)
from mytable
group by grouping sets ((location), (location, class));

location | class | count
----------+---------+-------
Wakanda | priest | 1
Wakanda | tank | 2
Wakanda | warrior | 3
Wakanda | | 6
(4 rows)

或一个位置的单行,例如:

select
max(count) as units,
location,
string_agg(class || ': ' || count, ', ') as counts
from (
select location, class, count(*)
from mytable
group by grouping sets ((location), (location, class))
) s
group by location;

units | location | counts
-------+----------+--------------------------------
6 | Wakanda | priest: 1, tank: 2, warrior: 3
(1 row)

关于sql - 如何计算sql中聚合中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50815997/

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