2015-11-25 70 views
1

我正在嘗試從表中每日計數總和中獲取最大行數。我看過幾篇看起來很相似的帖子,但似乎沒有用。我試圖按照 Get MAX row for GROUP in MySQL 但它不起作用在Postgres。下面是我有Postgresql按列獲得最大行數

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" 
+0

'組由源,TO_CHAR( 「結束時間」 ::日, 'MM/DD/YYYY')'你似乎來自另一個星球。 'endTime :: date'有什麼問題?)? – wildplasser

+0

我需要的日期格式是特定的用戶 – user2974739

回答

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; 
+0

這工作。謝謝。 – user2974739