2017-02-06 73 views
0

我有两个表 - featureinspectionSQL查询 - 每种类型的功能和检查类型的最新检查

要素表看起来是这样的:

id | name 
-----|----- 
1 | tree 
2 | flower 
... 

检查表看起来像这样:

id | feature_id | category | date_created 
---|------------|-------------|------------- 
1 | 1   | inspection | 10/10/2010 
2 | 1   | cleaned  | 10/20/2009 
3 | 3   | inspection | 1/1/2008 
4 | 1   | inspection | 1/1/2005 

如何创建一个查询,会给我最近一次检查在每个功能每个类别?

inspection_id | feature_id | date   | category 
--------------|------------|--------------|----------- 
1    | 1   | 10/10/2010 | inspection 
2    | 1   | 10/20/2009 | cleaned 
3    | 3   | 1/1/2008  | inspection 

回答

0

如果我理解正确,这只是从组中选择最近一行。最常见的方法使用row_number()

select i.* 
from (select i.*, 
      row_number() over (partition by feature_id, category order by date desc) as seqnum 
     from inspections i 
    ) i 
where seqnum = 1;