Postgresql逐列获取最大行

时间:2015-11-25 00:23:57

标签: sql postgresql greatest-n-per-group

我试图从表格中的每日计数总和中获取最大行数。我看过几个看起来很相似的帖子,但它似乎没什么用。我试过跟随 Get MAX row for GROUP in MySQL 但它在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')

返回以下内容

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"

我希望结果只返回源为daily_steps的最大值的行。结果应该看起来像

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

1 个答案:

答案 0 :(得分:1)

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;