2017-02-23 38 views
0

假设有一个数据收集系统,无论何时更改记录,它都会保存为带有前缀的新记录(例如M- [最近的数字在que中并且是唯一的]) 。通过迭代对原始值进行跟踪SQL

假设我给出的以下数据集:

Customer |   Original_Val 
    1     1020 
    2     1011 
    3     1001 

我需要找到下表给出了每一位客户最近的值:

Customer | Most_Recent_Val  | Pretained_To_Val |  date 
    1     M-2000     M-1050    20170225 
    1     M-1050     M-1035    20170205 
    1     M-1035     1020    20170131 
    1     1020      NULL    20170101 
    2     M-1031     1011    20170105 
    2     1011      NULL    20161231 
    3     1001      NULL    20150101 

我所需的输出是:

Customer | Original_Val  | Most_Recent_Val |  date 
    1     1020     M-2000    20170225 
    2     1011     M-1031    20170105 
    3     1001     1001    20150101 

对于顾客1,有4个等级即(M-2000 < - M- 1050 < - M-1035 < - 1020)请注意,每个客户的深度不会超过10层。

非常感谢!提前致谢。

回答

0

找到每个客户的最小和最大值,然后将其加入到一起。类似这样的:

Select 
    [min].Customer 
    ,[min].Most_Recent_Val as Original_Val 
    ,[max].Most_Recent_Val as Most_Recent_Val 
    ,[max].date 
From 
    (
     Select 
      Customer 
      ,Most_Recent_Val 
      ,date 
     From 
      table t1 
      inner join (
       Select 
        Customer 
        ,MIN(date) as MIN_Date 
       From 
        table 
       Group By 
        Customer 
      ) t2 ON t2.Customer = t1.Customer 
       and t2.MIN_Date = t1.Date 
    ) [min] 
    inner join (
     Select 
      Customer 
      ,Most_Recent_Val 
      ,date 
     From 
      table t1 
      inner join (
       Select 
        Customer 
        ,MAX(date) as MAX_Date 
       From 
        table 
       Group By 
        Customer 
      ) t2 ON t2.Customer = t1.Customer 
       and t2.MAX_Date = t1.Date 
    ) [max] ON [max].Customer = [min].Customer