简体   繁体   中英

SELECT latest record from a SQL Server 2008 table

I have a table which contains the terms of payment for a product. I want to get the latest terms for that product. In the query below it returns all the terms since my application went into production. I only need the latest term for that product.

SELECT
   dbo.FinishProduct.id,
   dbo.PaymentTerm.id,
   dbo.PaymentTerm.terms,
   dbo.PaymentTerm.type
FROM
   dbo.PaymentTerm
INNER JOIN
   dbo.FinishProduct ON (dbo.PaymentTerm.finishProductId = dbo.FinishProduct.id) 
WHERE
   finishproduct.id = 39

My PaymentTerm table has PK id and it has date when it was created and updated, like this:

id BIGINT NOT NULL IDENTITY,
created DATETIME,
lastUpdated DATETIME,

You can put orderby clause on lastUpdated field in query and get the top 10 or more latest record accordingly as follows

SELECT TOP 10  FP.id, PT.id, PT.terms, PT.type
  FROM dbo.PaymentTerm PT
  INNER JOIN dbo.FinishProduct FP ON PT.finishProductId = FP.id 
  WHERE FP.id=39
  ORDER BY lastUpdated desc

Or if you need to get all records from one day back to current date use DateDiff in built function like this

SELECT FP.id, PT.id, PT.terms, PT.type
  FROM dbo.PaymentTerm PT
  INNER JOIN dbo.FinishProduct FP ON PT.finishProductId = FP.id 
  WHERE FP.id=39 AND DateDiff(DAY,lastUpdated, GETDATE()) <= 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM