我有一个包含以下列的表
部分数据可能如下所示:
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
我想运行一个查询,为每个不同的ForeignKeyId和AttributeName提取AttributeValue列的最新值,使用Created列确定最近的值。示例输出将是:
ForeignKeyId AttributeName AttributeValue Created
-------------------------------------------------------
1 'EmailPreference' 'Text' 1/10/2010
2 'EmailPreference' 'Html' 1/8/2010
如何使用SQL Server 2005执行此操作?
答案 0 :(得分:21)
单程
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
另请参阅Including an Aggregated Column's Related Values了解执行此类查询的5种不同方法
答案 1 :(得分:9)
使用:
SELECT x.foreignkeyid,
x.attributename,
x.attributevalue,
x.created
FROM (SELECT t.foreignkeyid,
t.attributename,
t.attributevalue,
t.created,
ROW_NUMBER() OVER (PARTITION BY t.foreignkeyid, t.attributename
ORDER BY t.created DESC) AS rank
FROM TABLE t) x
WHERE x.rank = 1
使用CTE:
WITH summary AS (
SELECT t.foreignkeyid,
t.attributename,
t.attributevalue,
t.created,
ROW_NUMBER() OVER (PARTITION BY t.foreignkeyid, t.attributename
ORDER BY t.created DESC) AS rank
FROM TABLE t)
SELECT x.foreignkeyid,
x.attributename,
x.attributevalue,
x.created
FROM summary x
WHERE x.rank = 1
此外:
SELECT t.foreignkeyid,
t.attributename,
t.attributevalue,
t.created
FROM TABLE t
JOIN (SELECT x.foreignkeyid,
x.attributename,
MAX(x.created) AS max_created
FROM TABLE x
GROUP BY x.foreignkeyid, x.attributename) y ON y.foreignkeyid = t.foreignkeyid
AND y.attributename = t.attributename
AND y.max_created = t.created