PostgreSQL中针对特定ID的多个最大值选择

时间:2018-07-24 09:33:40

标签: sql postgresql

我有一张这样的桌子:

ID  cbk           due_16_30        due_31_60 
  1  2018-06-19    5                200
  2  2018-06-19    100              -5
  1  2018-06-19    -2               2
  2  2018-06-18    20               Null
  2  2018-06-18    50               22
  1  2018-06-18    30               150
  3  2018-06-18    20               70

我想为每个特定的ID和最近的日期选择一个最大的due_16_30和一个最大的due_31_60,其中日期介于某个start date和{{1}之间}。如何在PostgreSQL中做到这一点?

附言这是解决第二部分的方法:https://stackoverflow.com/a/51493567/8495108

4 个答案:

答案 0 :(得分:1)

一种方法使用distinct on

select distinct on (id) id, max(due_16_30), max(due_31_60) 
from t
where date >= ? and date < ?
group by id, date
order by id, date desc;

答案 1 :(得分:0)

您可以:

select t.id, t.cbk, max(t.due_16_30), max(t.due_31_60)
from table t
where cbk = (select t1.cbk
             from table t1
             where t1.cbk >= start_dt and t1.cbk <= end_dt
             order by t1.cbk desc
             limit 1
            )
group by t.id, cbk
order by t.id desc
limit 1;

答案 2 :(得分:0)

You need to consider myID parameter for both subquery and outer query as :

select ID,
       cbk,
       max(due_16_30) as max_due_16_30, 
       max(due_31_60) as max_due_31_60
  from tab
 where cbk in 
(
  select max(cbk)
    from tab 
   where cbk between start_date and end_date
     and ID = myID
)
   and ID = myID
 group by ID, cbk;

We may try for id = 3 in the demo, since there's no id = 3 for the latest date 2018-06-19 for whole table :

DB-Fiddle Demo

答案 3 :(得分:0)

已解决(简化)

SELECT v.id, max(v.due_31_60), max(v.due_61_90), v.cbk
      FROM my_table as v
      JOIN (select id, max(cbk) as max_date from my_table
           WHERE (cbk >= start_date and cbk <= end_date ) 
           GROUP BY id) as q 
      ON q.id = v.id and v.cbk = q.cbk
      GROUP BY v.id, v.cbk