Select all rows with the highest (relative) timestamp

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

Given a specific one AppName, show me all the ONLY LAST Key / Value pairs whoseEffectiveDate <= GetDate()

So, if I called my secret request with AppName = 'App1', then my results:

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

EDIT:

The value can be any. (“Past,” “Present,” “Future”) were simply used to make this example clearer. They could very well be (45, "Bob", "% $ #% @ # $").

+3
source share
4 answers

, - :

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
+3

- , .

SELECT *
FROM your_table
WHERE AppName = 'App1'
AND DATE = (SELECT MAX(EffectiveDate ) 
             FROM your_table
             WHERE APPName = 'App1'
              AND EffectiveDate <= GetDate())
+2

SQL-:

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

There are a lot of information in SQL queries, but it's a pretty good starter: http://www.w3schools.com/sql/sql_where.asp

0
source

You need to determine what the "Real" is. Is this the last year? Last decade?

Your request will look as follows

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'
0
source

Source: https://habr.com/ru/post/1772898/


All Articles