Postgresql逐列获取最大行

时间:2021-05-29 12:33:08

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. Here's what I have

我试图从表格中的每日计数总和中获取最大行数。我看过几个看起来很相似的帖子,但它似乎不起作用。我试图在MySQL中关注Get MAX行,但它在Postgres中不起作用。这就是我所拥有的

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. The result should look like

我希望结果只返回源为daily_steps的最大值的行。结果应该是这样的

source, daily_steps, step_date
"walking";821;"11/22/2015"
"running";600;"11/24/2015"

1 个解决方案

#1


1  

Postgres offers the convenient distinct on syntax:

Postgres提供了方便的独特语法:

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;

#1


1  

Postgres offers the convenient distinct on syntax:

Postgres提供了方便的独特语法:

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;