Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在postgresql中计算字符串聚合中的字符串数_Sql_String_Postgresql - Fatal编程技术网

如何在postgresql中计算字符串聚合中的字符串数

如何在postgresql中计算字符串聚合中的字符串数,sql,string,postgresql,Sql,String,Postgresql,因此,我有一个表,我正在使用其他列(如邮政编码)对其进行分组,我想聚合一些字符串,并知道它们的类型,使用字符串聚合函数string_aggdistinct column,,“order by column”非常容易 问题是,通过这样做,我不知道每种类型有多少字符串被聚合 如果我的桌子看起来像: column A Banana Monkey Banana Thailand Banana Monkey 我当前的聚合返回一个带有[香蕉、猴子、泰国]的字段 实际上,我希望在同一个字段上

因此,我有一个表,我正在使用其他列(如邮政编码)对其进行分组,我想聚合一些字符串,并知道它们的类型,使用字符串聚合函数string_aggdistinct column,,“order by column”非常容易

问题是,通过这样做,我不知道每种类型有多少字符串被聚合

如果我的桌子看起来像:

column A 

Banana 

Monkey

Banana

Thailand

Banana

Monkey
我当前的聚合返回一个带有[香蕉、猴子、泰国]的字段

实际上,我希望在同一个字段上的输出是[3个香蕉,2个猴子,1个泰国]

我当前的非工作聚合查询如下所示

create table test as select count(a.*), STRING_AGG(cnt::text || ' ' || col, ', ' order by col), a.postcode, a.geom 
FROM tablewithdata a, 
(select col, COUNT(*) AS cnt, postcode, geom FROM tablewithdata 
GROUP BY col, postcode, geom) x 
group by a.postcode, a.geom

是否可以实现此输出?

一个选项是首先传递表格并生成计数,然后将所有内容聚合在一起:

WITH cte AS (
    SELECT col, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY col
)

SELECT STRING_AGG(cnt::text || ' ' || col, ', ' order by col)
FROM cte;

3 Banana, 2 Monkey, 1 Thailand

一种选择是,首先传递表并生成计数,然后将所有内容聚合在一起:

WITH cte AS (
    SELECT col, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY col
)

SELECT STRING_AGG(cnt::text || ' ' || col, ', ' order by col)
FROM cte;

3 Banana, 2 Monkey, 1 Thailand

因此,我试图在from中的子查询中实现您的查询,但这确实需要很长时间。代码看起来类似于创建表测试作为select counta.*,STRING_AGGcnt::text | |‘|‘| | col’,‘按列排序,a.postcode,a.geom FROM tablewithdata a,select col,COUNT*作为cnt,postcode,geom FROM tablewithdata GROUP by col,postcode,geom x GROUP by a.postcode,a.geom有更好的输入方法吗?@Luffydude,你可能想提出一个新问题。您尝试执行的操作与您上面要求的操作看起来非常不同。我希望获得每个聚合字符串的计数,如果它们与我的分组无关,我将无法使用它们,否则,我只需要一个count列,而不需要首先进行字符串聚合,因此我尝试在from中的子查询中实现您的查询,但这确实需要很长时间。代码看起来类似于创建表测试作为select counta.*,STRING_AGGcnt::text | |‘|‘| | col’,‘按列排序,a.postcode,a.geom FROM tablewithdata a,select col,COUNT*作为cnt,postcode,geom FROM tablewithdata GROUP by col,postcode,geom x GROUP by a.postcode,a.geom有更好的输入方法吗?@Luffydude,你可能想提出一个新问题。您尝试执行的操作与您上面要求的操作看起来非常不同。我希望获得每个聚合字符串的计数,如果它们与我的分组无关,我将不使用它们,否则我将只使用计数列,而不需要首先进行字符串聚合