如何在Postgresql中使用ARRAY_AGG计算子查询中的数组元素?

o75abkj4  于 2023-03-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(176)

初始查询查找每个feature_id所应用的语言,并将结果放入数组中。我想计算每个区域、每个feature_id、每个版本(新版本和旧版本)中的语言数量。

SELECT
  array_length(applied_languages_in_old_version, 1) AS COUNT1,
  array_length(applied_languages_in_new_version, 1) AS COUNT2
FROM (
SELECT
  t1.feature_id,
  t1.territory_type,
  t1.territory_category,
  (array_agg(DISTINCT t2.language), ', ') AS applied_languages_in_old_version,
  (array_agg(DISTINCT t4.language), ', ') AS applied_languages_in_new_verison
FROM kh_bel_territory_2023mar14.kh_bel_territory_2023mar14_territory t1
LEFT OUTER JOIN kh_bel_territory_2023mar14.kh_bel_territory_2023mar14_territory_name t2
ON t1.feature_id = t2.feature_id AND t2.name_type = 'PRIMARY_FOR_LANGUAGE'
JOIN kh_bel_territories_08nov2022.kh_bel_territories_08nov2022_territory t3
ON t1.feature_id = t3.feature_id
LEFT OUTER JOIN kh_bel_territories_08nov2022.kh_bel_territories_08nov2022_territory_name t4
ON t1.feature_id = t4.feature_id AND t4.name_type = 'PRIMARY_FOR_LANGUAGE') a
GROUP BY
  t1.feature_id,
  t1.territory_type,
  t1.territory_category
ORDER BY t1.feature_id;

**结果:**错误:列“t1.feature_id”必须出现在GROUP BY子句中或在聚合函数中使用

nukf8bse

nukf8bse1#

正如错误消息所述,select中的所有列都必须在GROUP BY中或使用聚合函数,我认为您可以使用MAX,但这可能是对您正在寻找的内容的误解

SELECT
  MAX(array_length(applied_languages_in_old_version, 1)) AS COUNT1,
  MAX(array_length(applied_languages_in_new_version, 1)) AS COUNT2
FROM (
SELECT
  t1.feature_id,
  t1.territory_type,
  t1.territory_category,
  (array_agg(DISTINCT t2.language), ', ') AS applied_languages_in_old_version,
  (array_agg(DISTINCT t4.language), ', ') AS applied_languages_in_new_verison
FROM kh_bel_territory_2023mar14.kh_bel_territory_2023mar14_territory t1
LEFT OUTER JOIN kh_bel_territory_2023mar14.kh_bel_territory_2023mar14_territory_name t2
ON t1.feature_id = t2.feature_id AND t2.name_type = 'PRIMARY_FOR_LANGUAGE'
JOIN kh_bel_territories_08nov2022.kh_bel_territories_08nov2022_territory t3
ON t1.feature_id = t3.feature_id
LEFT OUTER JOIN kh_bel_territories_08nov2022.kh_bel_territories_08nov2022_territory_name t4
ON t1.feature_id = t4.feature_id AND t4.name_type = 'PRIMARY_FOR_LANGUAGE') a
GROUP BY
  t1.feature_id,
  t1.territory_type,
  t1.territory_category
ORDER BY t1.feature_id;

相关问题