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

标签 sql postgresql

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

我的聚合查询如下:

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/

相关文章:

database - 恢复超过 20gb 的 postgres sql 文件

MySQL SELECT all 除了两列有特定数据的地方

mysql - 优化 SELECT COUNT(DISTINCT(col)) var, col2 var2 FROM table WHERE col< >'X' and col2 between 'Y' and 'Z' GROUP BY var2 ORDER BY var DESC;为了速度?

sql - 有没有更好的方法来区分没有 child 或无效的 parent 身份?

python - Django 中的 ManyToMany 慢

sql - 在sql中的某些单词之间选择数字

sql - PostgreSQL 在外键中使用常量

sql - 如何在左连接中获取另一个表的计数

sql - 如何创建带参数的 SQL 函数?

sql - Parenthesis() 和 SQL 查询性能