SQL Server 仅使用最近的值选择不同的行
Posted
技术标签:
【中文标题】SQL Server 仅使用最近的值选择不同的行【英文标题】:SQL server select distinct rows using most recent value only 【发布时间】:2011-03-27 10:55:56 【问题描述】:我有一个包含以下列的表格
身份证 外键ID 属性名 属性值 已创建部分数据可能如下所示:
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 做到这一点?
【问题讨论】:
EmailPreference/Text/ 1/10/2010 的值不应该是 3,而不是 1? 不,输出的第一列是外键id,不是行id 【参考方案1】:一种方式
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 种不同方式
【讨论】:
如果 created/MaxCreated 不是唯一的,那么您仍然会得到多个结果。可以避免吗?【参考方案2】:用途:
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
【讨论】:
以上是关于SQL Server 仅使用最近的值选择不同的行的主要内容,如果未能解决你的问题,请参考以下文章