从SQL Server 2008表中选择最新记录

时间:2012-08-26 05:03:55

标签: sql sql-server

我有一张表格,其中包含产品的付款条件。我想获得该产品的最新条款。在下面的查询中,它返回自我的应用程序投入生产以来的所有术语。我只需要该产品的最新术语。

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

我的PaymentTerm表格有PK id,并且它有创建和更新日期,如下所示:

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

1 个答案:

答案 0 :(得分:1)

您可以在查询中的lastUpdated字段中放置orderby子句,并相应地获取前10个或更多最新记录,如下所示

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

或者如果您需要将所有记录从一天恢复到当前日期,请在构建函数中使用DateDiff,如下所示

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