我在SQL 2000 Databse中具有以下简化的表结构:

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','%$#%@#$')。

最佳答案

我认为您需要使用以下内容:

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

10-06 12:51