SQL Server在特定日期之前使用值选择不同的行

时间:2013-11-06 08:46:10

标签: sql sql-server sql-server-2008

三年前有一个问题得到了充分的回答,所以我不想污染它,因为这是对这个问题的延伸。先前的问题是this

好的,我有一个包含以下列的表

  • 编号
  • ForeignKeyId
  • 的AttributeName
  • 的AttributeValue
  • 创建

部分数据可能如下所示:

ID, ForeignKeyId, AttributeName,    AttributeValue, Created
1,    1,         'EmailPreference',   'Text',       1/1/2010
2,    1,         'EmailPreference',   'Html',       1/3/2010
3,    1,         'EmailPreference',   'Text',       1/10/2010
4,    2,         'EmailPreference',   'Text',       1/2/2010
5,    2,         'EmailPreference',   'Html',       1/8/2010

我想运行一个查询,告诉我指定REQUEST_DATE的最新“创建”日期 对于每个不同的ForeignKeyId和AttributeName,使用Created列确定最新值。

CreatedDate为'1/4/2010'的示例输出为:

ForeignKeyId AttributeName    AttributeValue Created
-------------------------------------------------------
1           'EmailPreference' 'Text'         1/2/2010
2           'EmailPreference' 'Html'         1/3/2010

CreatedDate为'1/9/2010'的示例输出为:

ForeignKeyId AttributeName    AttributeValue Created
-------------------------------------------------------
1           'EmailPreference' 'Text'         1/2/2010
2           'EmailPreference' 'Html'         1/8/2010

如何使用SQL Server 2008执行此操作?

到目前为止,我有:

DECLARE @REQUEST_DATE varchar(10)
SELECT @REQUEST_DATE = '1/9/2010'

select t1.* from (select ForeignKeyId,AttributeName, max(Created) AS MaxCreated
  from  YourTable
group by ForeignKeyId,AttributeName) t2
join YourTable t1 on 
   t2.ForeignKeyId = t1.ForeignKeyId
   and t2.AttributeName = t1.AttributeName
   and t2.MaxCreated = t1.Created

但我无法确定将限制放在何处仅包括在请求日期之前包含'已创建'的行

1 个答案:

答案 0 :(得分:1)

DECLARE @REQUEST_DATE varchar(10)
SELECT @REQUEST_DATE = '1/9/2010'

select t1.* from (select ForeignKeyId,AttributeName, max(Created) AS MaxCreated
  from  YourTable
where created < @REQUEST_DATE
group by ForeignKeyId,AttributeName) t2
join YourTable t1 on 
   t2.ForeignKeyId = t1.ForeignKeyId
   and t2.AttributeName = t1.AttributeName
   and t2.MaxCreated = t1.Created
相关问题