由不同的字符PostgreSQL聚合

时间:2016-12-19 19:11:58

标签: sql postgresql

我的表zone_dist中有parcel16列,其中包含土地使用代码(字符)。我的目标是创建一个双列表,在左侧列中显示所有不同的值,在右侧显示表中这些值的总计数,按降序排列。我尝试过基本查询但不能将sum函数应用于字符值:

SELECT  zone_dist, SUM(zone_dist) AS quantity
FROM parcel16
GROUP BY zone_dist

返回错误:

ERROR:  function sum(character varying) does not exist
LINE 1: SELECT  zone_dist, SUM(zone_dist) AS quantity
                           ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

如何获取所有不同字符值的计数?

3 个答案:

答案 0 :(得分:1)

你想要Count()而不是Sum()。 Sum()添加聚合值(假设为int),而Count()将计算您分组的值的数量。

SELECT  zone_dist, count(zone_dist) AS quantity
FROM parcel16
GROUP BY zone_dist
order by count(zone_dist) desc

答案 1 :(得分:0)

Sum对字符串数据进行数学运算。

对于每次出现的zone_dist,计数只需增加1。 (因此它忽略了空值)

SELECT  zone_dist, count(zone_dist) AS quantity
FROM parcel16
GROUP BY zone_dist

答案 2 :(得分:0)

  • 如果我们在列zone_dist中有NULL值,count(zone_dist)将不计算它们,而是返回0
  • quantity别名可以在order by子句
  • 中使用
select   zone_dist, count(*) as quantity 
from     parcel16 
group by zone_dist 
order by quantity desc