2010-08-09 19 views
16

Ho una tabella che ha le seguenti colonneSQL server selezionare righe distinte utilizzando più valore recente solo

  • Id
  • ForeignKeyId
  • AttributeName
  • AttributeValue
  • Creato

Alcuni dei dati potrebbero essere:

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 

Vorrei eseguire una query che tira il valore più recente della colonna AttributeValue per ogni distinto ForeignKeyId andAttributeName, utilizzando la colonna creata per determinare il valore più recente. L'output di esempio sarebbe:

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

Come posso farlo utilizzando SQL Server 2005?

+0

Il valore non deve essere 3, non 1, per EmailPreference/Text/1/10/2010? –

+0

No, la prima colonna nell'output è l'ID della chiave esterna, non l'ID della riga – Chris

risposta

18

Un modo

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 

Vedi anche Including an Aggregated Column's Related Values per 5 diversi modi per fare questo tipo di interrogazione

+0

Questo è un collegamento informativo. Grazie! –

9

Usa:

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 

Utilizzando un 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 

Inoltre:

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 
Problemi correlati