如何保留每个唯一ID的最新记录

时间:2020-07-23 02:32:47

标签: sql greatest-n-per-group

我有一个名为“ DB”的小表,其中包含以下字段:ID,RDate,TYear,TRate

SELECT DB.ID, DB.RevDate, DB.TrendYear, DB.TrendRate
FROM DB
WHERE (((DB.TrendYear)>=2000))
ORDER BY DB.ID, DB.TrendYear;
ID  RDate      TYear   TRate    
1   12/1/2013  2000    6.60%    
1   12/1/2011  2000    6.60%    
1   8/1/2010   2001    2.43%    
1   12/1/2012  2001    2.43%    
1   7/1/2015   2002    10.16%   
1   12/1/2012  2002    10.16%   
1   8/1/2010   2002    10.16%   
1   12/1/2011  2003    1.36%    
1   7/1/2016   2003    1.36%
1   8/1/2010   2000    6.60%  
1   12/1/2012  2000    6.60%
1   12/1/2013  2001    2.43%
1   7/1/2015   2001    2.43%
1   12/1/2011  2001    2.43%
1   2/1/2013   2002    10.16%
1   2/1/2011   2002    10.16%
1   /1/2010    2003    1.36%
1   12/1/2013  2003    1.36%
2                               

我运行了上述SQL代码并获得了上表。如何仅将每个“ TYear”和每个“ ID”的“ TRate”与最新的“ RDate”相对应?

例如:

ID  RDate      TYear   TRate 
1  12/1/2013   2000    6.60% 
1  7/1/2015    2001    2.43% 
1  7/1/2015    2002    10.16% 
1  7/1/2016    2003    1.36% 
2   ...               
3...

2 个答案:

答案 0 :(得分:1)

只是吐口水,没有任何测试,但我会尝试...

SELECT
    ID,
    RevDate,
    TrendYear,
    TrendRate
FROM (
    SELECT
        DB.ID,
        DB.RevDate,
        DB.TrendYear,
        DB.TrendRate,
        MAX(DB.RevDate) OVER (PARTITION BY DB.ID, DB.TrendYear) MaxRevDate
    FROM
        DB
    WHERE
        (((DB.TrendYear)>=2000))
    ) S
WHERE
    S.MaxRevDate = S.MaxRevDate
ORDER BY
    ID,
    TrendYear;

答案 1 :(得分:0)

我为您的问题创建了一个示例。

  CREATE TABLE #DB2 (
  ID  int,
  RDate  varchar(10),
  TYear  int,
  TRate decimal(5,2)  
);

INSERT INTO #DB2
  (ID, RDate, TYear,TRate)
VALUES
  (1,'8/1/2010',2000 ,6.60),
  (1,'12/1/2013',2000 ,6.60),
  (1,'12/1/2012',2000 ,6.60),
  (1,'12/1/2011',2000 ,6.60),
  (1,'12/1/2013',2001 ,2.43),
  (1,'8/1/2010',2001 ,2.43),
  (1,'7/1/2015',2001 ,2.43),
  (1,'7/1/2015',2002 ,10.16),
  (1,'12/1/2013',2002  ,10.16)
  ;

  ;with CTE_select as ( SELECT #DB2.ID, #DB2.TYear, MAX(CONVERT(date,#DB2.RDate)) RDate FROM #DB2 group by ID,TYear)

 select  list.ID,list.RDate,list.TYear,list.TRate   from #DB2 list   inner  join  CTE_select cte   on ( cte.ID = list.ID and cte.TYear = list.TYear and cte.RDate = list.RDate)

结果=

ID  RDate       TYear   TRate
1   12/1/2013   2000    6.60
1   7/1/2015    2001    2.43
1   7/1/2015    2002    10.16