Path: csiph.com!x330-a1.tempe.blueboxinc.net!feeder1.hal-mli.net!feeder.news-service.com!85.214.198.2.MISMATCH!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Erland Sommarskog Newsgroups: comp.databases.ms-sqlserver Subject: Re: Query for record that is effective as of a certain date Date: Mon, 16 May 2011 22:29:35 +0200 Organization: Erland Sommarskog Lines: 29 Message-ID: References: <2d2ba1e2-e68b-4292-8bac-e8af30fe3ebb@q20g2000vbx.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252 Content-Transfer-Encoding: 8bit Injection-Info: mx04.eternal-september.org; posting-host="DD6dU+BfJNjsjSP4/K/V7w"; logging-data="27985"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19ZoQnd0uK/SEmcIeAk6Je9" User-Agent: Xnews/2006.08.24 Mime-proxy/2.1.c.0 (Win32) Cancel-Lock: sha1:9ENGc5BnKuAO6I1bfKNd1MjNDMI= Xref: x330-a1.tempe.blueboxinc.net comp.databases.ms-sqlserver:334 BobRoyAce (broy@omegasoftwareinc.com) writes: > How could I construct such a query? Is this something I could do with > Select...Over...Partition By? I am not very familiar with that > construct, but it seems that it might be relevant. row_number is indeed your guy. WITH numbered AS ( SELECT fkLoanId, fkLoanStatusID, EffectiveDate, rowno = row_number() OVER (PARTITION BY fkLoanId ORDER BY EffectiveDate DESC) FROM LoanStatusChanges WHERE EffectiveDate <= @perdate ) SELECT L.LoanNum, LS.LoanStatusDesc, n.EffectiveDate FROM numbered n JOIN Loans L ON n.LoanID = L.LoanID JOIN LoanStatuses LS ON n.LoanStatusID = LS.LoanStatusID WHERE rowno = 1 -- Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se Links for SQL Server Books Online: SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx