简单sql(我希望如此!)

简单sql(我希望如此!),sql,postgresql,group-by,greatest-n-per-group,Sql,Postgresql,Group By,Greatest N Per Group,给定与此类似的数据集: 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 我想通过“时间”获取每个ccy的最新fxrates: ccy | time | fxrate GBP | 20 | 1.9 EUR | 21 | 1.4

给定与此类似的数据集:

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
我想通过“时间”获取每个ccy的最新fxrates:

ccy | time | fxrate
GBP | 20   | 1.9
EUR | 21   | 1.4
CHF | 9    | 3.1
是否可以通过单个sql查询获取此数据?我的技能越来越差。我想我需要按ccy分组。。?maxtime在哪里。。?限制1。。?救命啊

[编辑]使用postgresql

是的,您可以使用group by仅用于最大fxrate,但在您的情况下,您需要一个相关的子查询:

select t.*
from table t
where t.fxrate = (select max(t1.fxrate) from table t1 where t1.ccy = t.ccy);
在postgresql中,您可以执行以下操作:

select distinct on (ccy) *
from table t
order by t.fxrate desc;
是的,您可以仅对最大fxrate使用group by,但在您的情况下,您需要一个相关子查询:

select t.*
from table t
where t.fxrate = (select max(t1.fxrate) from table t1 where t1.ccy = t.ccy);
在postgresql中,您可以执行以下操作:

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

行号可能会有帮助

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

行号可能会有帮助

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

您还可以在子查询中使用内部联接,以按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

您还可以在子查询中使用内部联接,以按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

“time”列我没有意识到那些整数值是时间戳。可能是@jarlh的重复谢谢-我只是尽量简化数据集。可能太多了。时间栏我没有意识到那些整数值是时间戳。可能是@jarlh的重复谢谢-我只是尽量简化数据集。可能太多了。它在第1个版本中可以正常工作,但我正努力阻止它进行全表扫描,所以速度很慢。现在开始使用索引。@pomo尝试第二个查询,因为它比第一个查询好得多,但是将order by更改为order by ccy,time desc-这应该是正确且快速的。谢谢。这似乎奏效了。不过速度很慢。它正在做一个全表扫描。我想我缺少了一个索引。它在第1个版本中工作,但我很难阻止它进行完整的表扫描,所以速度很慢。现在开始使用索引。@pomo尝试第二个查询,因为它比第一个查询好得多,但是将order by更改为order by ccy,time desc-这应该是正确且快速的。谢谢。这似乎奏效了。不过速度很慢。它正在做一个全表扫描。我想我漏掉了一个索引。谢谢,但是速度太慢了。它正在做一个全表扫描,尽管我认为我已经有了正确的索引。谢谢,但是速度非常慢。它正在做一个完整的表扫描,即使我认为我有正确的索引。