Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I am fairly new to SQL, but I am advancing quite well.I am modifying a table to store previous revisions of an item. I have come up with a new schema that can store this (feel free to offer reccomendations here too), but now I need help writing a Query that takes into account the Revisions.Original Schema---------------Items Table- ID (int) Primary Key - Type (int) Foreign Key - can NOT change per revision- Name (string) - can change per revision- other fields - can change per revisionNew Schema---------- Items Table- ID (int) Primary Key - Type (int) Foreign KeyItemFields Table- ID (int) Foreign Key to Item Table- Name (string)- other fields- RevDate (datetime)I used to query all the Items simply:SELECT * FROM ItemsID__Type__Name1___1_____'Item1'2___1_____'Item2'Now I want to select only the last revision of each Item.SELECT * FROM ItemFieldsID__Name_____RevDate1___'Item1'___12/1/081___'MyItem'__12/30/082___'Item2'___12/1/08... should return two items, 'MyItem' & 'Item2'.How do I write this query?
[code]SELECT i.*FROM ItemFields iINNER JOIN (SELECT ID,MAX(RevDate) AS Latest FROM ItemFields GROUP BY ID)i1ON i1.ID=i.IDAND i1.Latest=i.RevDate[/code]
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2008-12-30 : 14:05:33
or even this
SELECT t.ID,t.Name,t.RevDateFROM(SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY RevDate DESC) AS Seq,*FROM ItemFields)tWHERE t.Seq=1