0

我一直在试图弄清楚如何只选择最近的日期值

SELECT TOP (100) PERCENT 
    dbo.StockStatusHistory.StockID AS Expr1, 
    dbo.Stock.StockNo, dbo.CardFile.CardName AS SalesPerson, 
    dbo.Stock.Description, dbo.Stock.Retail, 
    dbo.Stock.SaleOrderDate, dbo.Stock.WarrantyStartDate, dbo.Stock.SaleNotes, 
    dbo.Stock.ManuMonth, dbo.Stock.ManuYear, dbo.Stock.InspCertDate, 
    dbo.Stock.StockStatus, dbo.StockStatusHistory.NewStockStatus, 
    dbo.StockStatusHistory.ChangeDate AS Expr2, 
    dbo.StockStatusHistory.ID, dbo.CardFile.CardId, 
    dbo.Stock.SalesPersonId
FROM
    dbo.Stock 
INNER JOIN
    dbo.CardFile ON dbo.Stock.SalesPersonId = dbo.CardFile.CardId 
INNER JOIN
    dbo.StockStatusHistory ON dbo.Stock.StockId = dbo.StockStatusHistory.StockID
WHERE     
    (dbo.Stock.StockStatus = 30) AND (dbo.Stock.WarrantyStartDate >= { fn CURDATE() }) 
    AND (dbo.StockStatusHistory.NewStockStatus = 30) 
    OR (dbo.Stock.StockStatus = 30) AND (dbo.Stock.WarrantyStartDate IS NULL) 
    AND (dbo.StockStatusHistory.NewStockStatus = 30)

我尝试使用MAX(dbo.StockStatusHistory.StockID)但我想出了错误。

希望我的代码有意义。显然对 SQL 查询很陌生。

提前感谢安迪

4

1 回答 1

0

我不完全理解“最近的日期值”是什么意思,但我假设你想要基于某处日期字段的最新条目。

没有手头的模式很难说,但是您可以ORDER BY MyDate DESC在末尾创建一个,SELECT TOP 1 dbo.xxx在开头创建一个。

于 2013-09-21T00:45:21.117 回答