代码之家  ›  专栏  ›  技术社区  ›  Chris

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

  •  18
  • Chris  · 技术社区  · 14 年前

    我有一个包含以下列的表

    • 身份证件
    • 属性名
    • 属性值

    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列的最新值,使用创建的列来确定最新值。输出示例如下:

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

    如何使用SQLServer2005实现这一点?

    2 回复  |  直到 14 年前
        1
  •  22
  •   Mike Glenn    11 年前

    单向

    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种不同的查询方法

        2
  •  9
  •   OMG Ponies    14 年前

    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
    

    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