代码之家  ›  专栏  ›  技术社区  ›  Josh

选择时间戳最高(相对)的所有行

  •  3
  • Josh  · 技术社区  · 14 年前

    我在SQL 2000数据库中有以下简化的表结构:

    ID  AppName  Key    Value   EffectiveDate
    --  -------  -----  ------- -------------
    1   App1     One    Past    1/1/1900
    2   App1     One    Present 1/1/2010
    3   App1     One    Future  1/1/9999
    4   App1     Two    Past    1/1/1900
    5   App1     Two    Present 1/1/2010
    6   App1     Two    Future  1/1/9999
    7   App2     One    Present 1/1/2010
    8   App2     Two    Present 1/1/2010
    

    我需要能够提出以下问题:

    给定一个特定的 AppName ,全部给我看 只有最近的 键/值对 EffectiveDate <= GetDate()

    所以如果我用 AppName = 'App1' 那么我的结果是:

    ID  AppName  Key    Value   EffectiveDate
    --  -------  -----  ------- -------------
    2   App1     One    Present 1/1/2010
    5   App1     Two    Present 1/1/2010
    

    编辑:

    价值可以是任何东西。(‘过去’、‘现在’、‘未来’)只是用来让例子更清楚。他们很可能是(45,'bob','%$.%@.')。

    4 回复  |  直到 14 年前
        1
  •  3
  •   Mark Byers    14 年前

    我认为你需要用这样的东西:

    SELECT T3.*
    FROM your_table T4
    JOIN
    (
        SELECT T2.[Key], T2.EffectiveDate, MAX(T2.ID) AS ID
        FROM your_table T2
        JOIN 
        (
            SELECT [Key], MAX(EffectiveDate) AS EffectiveDate
            FROM your_table
            WHERE AppName = 'App1'
            AND EffectiveDate <= GetDate()
            GROUP BY [Key]
        ) T1
        ON T1.[Key] = T2.[Key] AND T1.EffectiveDate = T2.EffectiveDate
        WHERE T2.AppName = 'App1'
        GROUP BY T2.[Key], T2.EffectiveDate
    ) T3
    ON T3.ID = T4.ID
    
        2
  •  2
  •   Turnkey    14 年前

    更像这样的事情来获取最新的相对日期。

    SELECT *
    FROM your_table
    WHERE AppName = 'App1'
    AND DATE = (SELECT MAX(EffectiveDate ) 
                 FROM your_table
                 WHERE APPName = 'App1'
                  AND EffectiveDate <= GetDate())
    
        3
  •  0
  •   Neil Barnwell    14 年前

    似乎是一个相当基本的SQL查询:

    select *
    from App
    where AppName = 'App1'
        and EffectiveDate <= GetDate()
    

    关于SQL查询有很多信息,但这是一个很好的开端: http://www.w3schools.com/sql/sql_where.asp

        4
  •  0
  •   Tim Coker    14 年前

    你需要定义“现在”是什么。是去年吗?过去十年?

    您的查询如下

    SELECT *
    FROM your_table
    WHERE EffectiveDate <= GetDate()
    --This is where you need to define what "Present" is
    AND EffectiveDate > DateAdd(YY, -1, GetDate()) 
    AND AppName = 'App1'