[英]Postgresql get max row group by column
I am trying to get the max row from the sum of daily counts in a table. 我试图从表中的每日计数的总和中获得最大的行。 I have looked at several posts that look similar, however it doesn't seem to work.
我看过几篇看起来相似的文章,但是似乎没有用。 I have tried to follow Get MAX row for GROUP in MySQL but it doesn't work in Postgres.
我尝试按照MySQL中GROUP的Get MAX行操作,但在Postgres中不起作用。 Here's what I have
这就是我所拥有的
select source, SUM(steps) as daily_steps, to_char("endTime"::date, 'MM/DD/YYYY') as step_date
from activities
where user_id = 1
and "endTime" <= CURRENT_TIMESTAMP + INTERVAL '1 day'
and "endTime" >= CURRENT_TIMESTAMP - INTERVAL '7 days'
group by source, to_char("endTime"::date, 'MM/DD/YYYY')
This returns the following 这将返回以下内容
source, daily_steps, step_date
"walking";750;"11/17/2015"
"walking";821;"11/22/2015"
"walking";106;"11/20/2015"
"running";234;"11/21/2015"
"running";600;"11/24/2015"
I would like the result to return only the rows that have the max value for daily_steps by source. 我希望结果仅按源返回具有daily_steps最大值的行。 The result should look like
结果应该看起来像
source, daily_steps, step_date
"walking";821;"11/22/2015"
"running";600;"11/24/2015"
Postgres offers the convenient distinct on
syntax: Postgres提供了方便的语法
distinct on
:
select distinct on (a.source) a.*
from (select source, SUM(steps) as daily_steps, to_char("endTime"::date, 'MM/DD/YYYY') as step_date
from activities a
where user_id = 1 and
"endTime" <= CURRENT_TIMESTAMP + INTERVAL '1 day' and
"endTime" >= CURRENT_TIMESTAMP - INTERVAL '7 days'
group by source, to_char("endTime"::date, 'MM/DD/YYYY')
) a
order by a.source, daily_steps desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.