Sql 如何返回好友数的总和?

Sql 如何返回好友数的总和?,sql,postgresql,Sql,Postgresql,properties是一个hstore列 我列出了每个用户的所有条目,只显示了最近的好友数,因此我需要先按用户id分组,然后按排序进行数组 现在,我想返回所有好友数的总和。所以在这种情况下,只有一行有4个 SELECT user_id, to_json((array_agg(properties -> 'friends_count' ORDER BY id DESC))[1]::int) AS friends_count FROM daily_statistics st GROUP B

properties
是一个hstore列

我列出了每个用户的所有条目,只显示了最近的
好友数
,因此我需要先按
用户id
分组,然后按
排序进行
数组


现在,我想返回所有
好友数的总和。所以在这种情况下,只有一行有4个

SELECT user_id,
  to_json((array_agg(properties -> 'friends_count' ORDER BY id DESC))[1]::int) AS friends_count
FROM daily_statistics st
GROUP BY user_id ORDER BY max(id) DESC;
结果:

 user_id | friends_count
---------+---------
     549 | 2
      16 | 2
(2 rows)
使用以下命令:

SELECT SUM(friends_count) AS total_friend_counts
    FROM
      (SELECT user_id,
              to_json((array_agg(properties -> 'friends_count' ORDER BY id DESC))[1]::int) AS friends_count
       FROM daily_statistics st
      GROUP BY user_id ORDER BY max(id) DESC
      )totalFriends

如果我删除
分组依据
如何从用户处获取最新条目?“因此,在本例中,只有一行4。”---在您的问题中,您对最新条目一无所知。如果我不分组依据,我将不止一次地计算用户的
好友数
列,假设同一用户有多个entry当frind\u count=4或您只需要friend\u count时,输出表中的user\u id是什么?否
user\u id
,我只想要sumI get:
错误:函数sum(json)不存在
第1行:选择sum(friends\u count)作为total_friend_counts
为什么要将friends_count转换为JSON?嗯,是的,可能不需要转换为jsonYes,只需使用count()即可,此查询对您有效。