如何返回friends_count的总和?

时间:2014-04-14 06:48:12

标签: sql postgresql

properties是一个hstore列。

我列出了每个用户的所有条目,并且只显示了最新的friends_count,因此我需要先按user_id进行分组,然后使用{{1}进行array_agg }。

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

friends_count

结果:

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;

1 个答案:

答案 0 :(得分:0)

使用此:

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