【问题标题】:Tracing original Value through Iteration SQL通过迭代 SQL 追踪原始值
【发布时间】:2017-07-14 11:19:33
【问题描述】:

假设有一个数据收集系统,每当记录被更改时,它就会被保存为带有前缀的新记录(例如 M-[que 中的最新数字并且是唯一的])。

假设给定以下数据集:

 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

非常感谢!提前致谢。

【问题讨论】:

  • 您使用的是哪个DBMS? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加标签postgresql、oracle、db2、sql-server、...

标签: sql recursion


【解决方案1】:

找出每个客户的最小值和最大值,然后将它们连接在一起。像这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2018-11-26
    • 1970-01-01
    • 2011-12-25
    • 2019-03-20
    相关资源
    最近更新 更多