如何在postgresql中计算MAX(SUM())特别是在

时间:2015-04-30 13:34:13

标签: sql postgresql aggregate-functions

我试图在PostgreSQL中获得MAX(SUM()),这在PostgreSQL中是不可能的。我试图通过任何方法获得结果,但无法获得所需的结果。我的桌子是这样的 -

CREATE TABLE user_transactions ( id integer NOT NULL, user_id bigint, credit_rupee numeric, created_at timestamp without time zone, );

这是样本数据

id credit_rupee user_id date 1 30 72873 2015-03-25 2 10 76296 2015-03-25 3 3 73130 2015-03-26 4 2 73142 2015-03-26 5 8.44 73145 2015-03-26 6 2 72911 2015-03-26 7 5 73158 2015-03-26 8 10 73067 2015-03-26 9 2 76296 2015-03-26 10 1 76296 2015-03-27 11 5.5 73042 2015-03-27 12 2 73042 2015-03-27

在此我希望获得具有特定日期的credit_rupee最高金额的用户。

我想要的结果是

user_id max date 72873 30 2015-03-25 73067 10 2015-03-26 73042 5.5 2015-03-27

问题是我无法选择所有三个user_id,max(),没有GROUP BY日期和user_id的日期,这使得很难得出上述结果。

我尝试了许多组合,例如 SELECT MAX(sum),user_id,date FROM( SELECT SUM(credit_rupee),user_id,DATE(created_at) FROM user_transactions GROUP BY user_id,DATE(created_at) ORDER BY DATE(created_at)) as m GROUP BY date ORDER BY date;

SELECT DISTINCT(user_id),max,date from( SELECT MAX(sum),user_id,date FROM( SELECT SUM(credit_rupee),user_id,DATE(created_at) FROM user_transactions GROUP BY user_id,DATE(created_at) ORDER BY DATE(created_at)) as m GROUP BY DATE,user_id ORDER BY date) as x GROUP BY date,user_id

等等,但无论如何尝试无法得到我想要的结果。 谁能帮助我如何得出结果呢? 感谢

1 个答案:

答案 0 :(得分:0)

此查询将为您提供您想要的内容:

SELECT user_id,
       credit_rupee,
       created_at from
  (SELECT
     rank() OVER (PARTITION BY created_at ORDER BY credit_rupee DESC) AS rank,
     user_id, credit_rupee, created_at
     FROM user_transactions ) sq
WHERE rank=1;