0

I have the following table with group members count:

CREATE TABLE "group_members_count" (
  group_id INTEGER,
  time     TIMESTAMP,
  members_count INTEGER
) 

I want to query members count for specific group and time interval (from, to) with custom period.

I wrote the following query:

SELECT 
  "group_id",
  date_trunc('day', "time") as period,
  max(count) as value
FROM
  "group_members_count"
WHERE
  "channel_id" IN (123, 124) AND ("time"::date >= '2017-11-02' AND "time"::date <= '2017-11-02')
GROUP BY 
  "period", "group_id"
ORDER BY
  "group_id", "period" 

As expected, I will get the maximum value per day, but I need the latest.

1
  • max(("time"::date) ?.. Commented Feb 20, 2018 at 12:49

1 Answer 1

1

One method is to use array_agg() and take the first element:

SELECT group_id,
       date_trunc('day', "time") as period,
       max(count) as value,
       array_agg(count order by "time" desc)[1]
FROM group_members_count
WHERE channel_id IN (123, 124) AND
      ("time"::date >= '2017-11-02' AND "time"::date <= '2017-11-02')
GROUP BY period, group_id
ORDER BY group_id, period
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.