1

我在 SQL Server 2008 中有 SQL 表,我想获取取决于其日期的最新记录。

我写了一个查询

  SELECT TOP 1 * 
    FROM ProductPrice
   WHERE ProductID = 1698
     AND EffectiveFrom <= '1/31/2013'
ORDER BY EffectiveFrom DESC

并且在数据库中有一条记录,其中包含日期 2013-01-31 12:12:49.000

现在我期待上面的查询将返回 1 条记录,但它没有返回任何内容我应该在查询中更改什么?

4

4 回答 4

1

关键是您的日期是日期时间......除非您通过强制转换/转换摆脱时间戳,或者更改您的 where 子句。2013-01-01 HH:MM:SS永远都是> 01/01/2013

  SELECT TOP 1 * 
    FROM ProductPrice
   WHERE ProductID = 1698
     AND CONVERT(CHAR(8), EffectiveFrom, 112) <= '20130101'
ORDER BY EffectiveFrom DESC 
于 2013-01-31T07:15:44.077 回答
1

因为表中的数据不仅包含日期,还包含时间

  SELECT TOP 1 * 
    FROM ProductPrice
   WHERE ProductID = 1698
     AND CAST(EffectiveFrom AS date) <= '1/31/2013'
ORDER BY EffectiveFrom DESC

或者

  SELECT TOP 1 * 
    FROM ProductPrice
   WHERE ProductID = 1698
     AND EffectiveFrom <= DATEADD(SECOND, 86399, '1/31/2013')
ORDER BY EffectiveFrom DESC 
于 2013-01-31T07:16:41.923 回答
0

问题是您将 '1/31/2013 00:00' 与 '1/31/2013 12:12' 进行比较 - 它小于该值。您需要将查询转换为:

SELECT TOP 1 *  
FROM ProductPrice 
WHERE  ProductID = 1698 
   AND CONVERT(DATE,EffectiveFrom) <= '1/31/2013' 
ORDER BY EffectiveFrom DESC 
于 2013-01-31T07:17:27.410 回答
0

请试试:

  SELECT TOP 1 * 
    FROM ProductPrice
   WHERE ProductID = 1698
     AND EffectiveFrom <= (CONVERT(DATETIME, '1/31/2013') + 1)
ORDER BY EffectiveFrom DESC

它没有被选中,因为日期时间值2013-01-31 12:12:49.000大于1/31/2013.

于 2013-01-31T07:22:10.650 回答