我有下表,小组成员数:
CREATE TABLE "group_members_count" (
group_id INTEGER,
time TIMESTAMP,
members_count INTEGER
)
我想查询具有自定义期间的特定组和时间间隔(从,到)的成员计数。
我写了以下查询:
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"
正如预期的那样,我每天都会获得最大值,但我需要最新。
答案 0 :(得分:1)
一种方法是使用array_agg()
并获取第一个元素:
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