提取最新的有效价值/利率

时间:2011-10-19 09:33:42

标签: sql-server

我有一个看起来像这样的表:

Month   | Year  | Rate
2011    | Jan   | 50
2011    | Jun   | 55 
2011    | Nov   | 53 

由于此表我想用于财务计算,我需要以下格式输出:

Month   | Year  | Rate
2011    | Jan   | 50
2011    | Feb   | 50
2011    | Mar   | 50
2011    | Apr   | 50
2011    | May   | 50
2011    | Jun   | 55
2011    | Jul   | 55
2011    | Aug   | 55
2011    | Sep   | 55
2011    | Oct   | 55
2011    | Nov   | 53
2011    | Dec   | 53

请帮助

1 个答案:

答案 0 :(得分:0)

声明的要点是这样的

  • 使用内存表将ID's添加到月份名称。
  • 将此表格与原始rates表格相结合,以使用现有rateNULL生成每个月。
  • 来自此SELECT表的
  • FullYearRates,并使用此表中的子选项检索不存在的费率。

SQL脚本

;WITH months ([ID], [Month]) AS (
  SELECT 1, 'Jan'
  UNION ALL SELECT 2, 'Feb'
  UNION ALL SELECT 3, 'Mar'
  UNION ALL SELECT 4, 'Apr'
  UNION ALL SELECT 5, 'May'
  UNION ALL SELECT 6, 'Jun'
  UNION ALL SELECT 7, 'Jul'
  UNION ALL SELECT 8, 'Aug'
  UNION ALL SELECT 9, 'Sep'
  UNION ALL SELECT 10, 'Oct'
  UNION ALL SELECT 11, 'Nov'
  UNION ALL SELECT 12, 'Dec'
)  
, Rates ([Year], [Month], [Rate]) AS (
  SELECT 2011, 'Jan', 50
  UNION ALL SELECT 2011, 'Jun', 55 
  UNION ALL SELECT 2011, 'Nov', 53 
)
, FullYear ([Year], [Month], [ID]) AS (
  SELECT  DISTINCT r.[Year], m.[Month], m.Id
  FROM    Rates r
          CROSS APPLY months m
)
, FullYearRates ([Year], [Month], [Rate], [ID]) AS (
  SELECT  fy.[Year], fy.[Month], r.[Rate], fy.ID
  FROM    FullYear fy
          LEFT OUTER JOIN Rates r ON r.[Month] = fy.[Month] AND r.[Year] = fy.[Year]
)
SELECT  r1.[Year]
        , r1.[Month]
        , [Rate] = (
            SELECT  Rate 
            FROM    FullYearRates fr
                    INNER JOIN (
                      SELECT  ID = MAX(ID) 
                      FROM    FullYearRates 
                      WHERE   ID <= r1.ID 
                              AND Rate IS NOT NULL
                    ) fm ON fm.ID = fr.ID                              
          )                    
FROM    FullYearRates r1