首页>Program>source

我有一个包含以下各列的表

  • 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

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

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

如何使用SQL Server 2005做到这一点?

最新回答
  • 2021-1-11
    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
    

    另请参阅包括聚合列的相关值,以了解执行这种查询的5种不同方式

  • 2021-1-11
    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
    

  • android:Google Maps Fragment在片段内返回null
  • java:Android:如何在创建列表时禁用列表项