我在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','%$#%@#$')。
答案 0 :(得分:3)
我认为你需要使用这样的东西:
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
答案 1 :(得分:2)
更像是为了得到最新的相对日期。
SELECT *
FROM your_table
WHERE AppName = 'App1'
AND DATE = (SELECT MAX(EffectiveDate )
FROM your_table
WHERE APPName = 'App1'
AND EffectiveDate <= GetDate())
答案 2 :(得分:0)
看起来像一个相当基本的SQL查询:
select *
from App
where AppName = 'App1'
and EffectiveDate <= GetDate()
有关SQL查询的大量信息,但这是一个非常好的入门者:http://www.w3schools.com/sql/sql_where.asp
答案 3 :(得分:0)
您需要定义“礼物”是什么。是去年了吗?过去十年?
您的查询将如下所示
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'