Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting all rows with highest (relative) timestamp

I have the following simplified table structure in a 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

I need to be able to ask the question:

Given a specific AppName, show me all ONLY THE MOST RECENT Key/Value pairs whose EffectiveDate <= GetDate()

So if I called my mystery query with AppName = 'App1' then my results would be:

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

EDIT:

Value can be anything. ('Past','Present','Future') were merely used to make the example more clear. They could very well have been (45,'Bob','%$#%@#$').

like image 532
Josh Avatar asked Jan 20 '26 08:01

Josh


2 Answers

I think you need to use something like this:

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
like image 107
Mark Byers Avatar answered Jan 23 '26 01:01

Mark Byers


Something more like this to get the latest relative date.

SELECT *
FROM your_table
WHERE AppName = 'App1'
AND DATE = (SELECT MAX(EffectiveDate ) 
             FROM your_table
             WHERE APPName = 'App1'
              AND EffectiveDate <= GetDate())
like image 41
Turnkey Avatar answered Jan 23 '26 00:01

Turnkey