simple sql (i hope!)

时间:2019-04-08 13:18:24

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

Given a data set similar to this:

ccy | time | fxrate
GBP | 11   | 1.2
EUR | 21   | 1.4
CHF | 9    | 3.1
GBP | 15   | 1.1
EUR | 20   | 1.5
CHF | 1    | 3.0
CHF | 7    | 3.0
GBP | 20   | 1.9

I want to get the latest fxrates (by 'time') for each ccy:

ccy | time | fxrate
GBP | 20   | 1.9
EUR | 21   | 1.4
CHF | 9    | 3.1

Is it possible to get this data with a single sql query? My skills are failing me. I assume I need to GROUP BY ccy..? where max(time) ..? LIMIT 1 ..? Help!

[EDIT] using postgresql

4 个答案:

答案 0 :(得分:4)

Yes you can use group by for only max fxrate but in your case you need a correlated subquery :

select t.*
from table t
where t.fxrate = (select max(t1.fxrate) from table t1 where t1.ccy = t.ccy);

In postgresql you can do :

select distinct on (ccy) *
from table t
order by t.fxrate desc;

答案 1 :(得分:2)

row_number can be helpful

select * from (select *,row_number()over(partition by ccy order by time desc) rn
from table_name
) a where a.rn=1

答案 2 :(得分:2)

You could also use an inner join on sub query for max time group by ccy

select m.ccy, m.time, m.fxrate 
from my_table  m
inner join  (
  select ccy, max(time) max_time  
  from my_table  
  group by ccy
) t on t.ccy = m.ccy and t.max_time = m.time

答案 3 :(得分:1)

select ccy , time ,fxrate 
from mytable
Inner join(SELECT max(time) maxtime, ccy
            FROM  mytable
            group by ccy ) MAXCCY on maxccy.maxtime = mytable.time and MAXCCY.ccy = mytable.ccy