简体   繁体   English

如何在SQL聚合中计算数字?

[英]How to count numbers in an aggregation in sql?

So I want to aggregate groups of points that share the same location and then count the number of each class that belongs to the point. 因此,我想汇总共享相同位置的点组,然后计算属于该点的每个类的数量。

My aggregation query is as follows: 我的聚合查询如下:

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

The outcome of this gives me a row of for example 这样的结果给了我例如

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

How do I aggregate it to show instead 如何汇总显示

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

If I understand correctly, you want two levels of aggregation: 如果我理解正确,则需要两个聚合级别:

select lc.location,
       string_agg(class || '(' || cnt || ')', ', ' order by cnt desc)
from (select location, class, count(*) as cnt
      from mytable
      group by location, class
     ) lc
group by lc.location;

I put the string in what I consider a more reasonable format. 我将字符串放入我认为更合理的格式。 It would look like: 'warrior (10), priest (5), tank (1)'. 它看起来像是:“战士(10),牧师(5),坦克(1)”。 It is ordered by the frequency. 按频率排序。 You can (of course) adjust the syntax to get some other format if you like. 当然,您可以根据需要调整语法以获取其他格式。

Example data: 示例数据:

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

Use grouping sets. 使用分组集。 You can easily get a nice tabular output: 您可以轻松获得漂亮的表格输出:

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)

or a single row for a location, eg: 或某个位置的一行,例如:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM