SQL Server仅使用最新值选择不同的行

Chr*_*ris 18 sql t-sql sql-server sql-server-2005 greatest-n-per-group

我有一个包含以下列的表

  • ID
  • ForeignKeyId
  • 为AttributeName
  • 的AttributeValue
  • 创建

部分数据可能如下所示:

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
Run Code Online (Sandbox Code Playgroud)

我想运行一个查询,为每个不同的ForeignKeyId和AttributeName提取AttributeValue列的最新值,使用Created列确定最新值.示例输出将是:

ForeignKeyId AttributeName    AttributeValue Created
-------------------------------------------------------
1           'EmailPreference' 'Text'         1/10/2010
2           'EmailPreference' 'Html'         1/8/2010
Run Code Online (Sandbox Code Playgroud)

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

SQL*_*ace 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
Run Code Online (Sandbox Code Playgroud)

另请参阅包含聚合列的相关值以了解执行此类查询的5种不同方法


OMG*_*ies 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
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)

也:

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
Run Code Online (Sandbox Code Playgroud)