次の列を持つテーブルがあります
一部のデータは次のようになります。
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
Created列を使用して最新の値を決定し、個別のForeignKeyIdおよびAttributeNameごとにAttributeValue列の最新の値を取得するクエリを実行したいと思います。出力例は次のようになります。
ForeignKeyId AttributeName AttributeValue Created
-------------------------------------------------------
1 'EmailPreference' 'Text' 1/10/2010
2 'EmailPreference' 'Html' 1/8/2010
SQL Server 2005を使用してこれを行うにはどうすればよいですか?
一方通行
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
この種のクエリを実行する5つの異なる方法については、 集計列の関連値を含む も参照してください。
使用する:
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