如何在两个日期日期之间查找特定记录

时间:2013-12-31 08:46:52

标签: sql

假设我有一个巨大的表格,可以使用以下格式从一开始就保存大量日志:

==========================================================
| Name | Log                      | Date (type datetime) |
----------------------------------------------------------
| Bob  | {Some:[sort,of,json]}    | 1-May-2013 09:12:45  |
| Josh | {Another:[sort,of,json]} | 1-May-2013 09:13:45  |
| Fred | {Yada:[yada,yada,yada]}  | 1-May-2013 09:14:45  |
| Josh | {Ahoy:[whee,whee,whee]}  | 1-May-2013 09:15:45  |
| Lucy | {Ahem:[blagh,blgh,blgh]} | 1-May-2013 09:16:45  |
| Bob  | {Chih:[aw,ew,ow]}        | 2-May-2013 09:12:45  |
..........................................................
| Fred | {Cheh:[saw,sew,sow]}     | 1-May-2014 09:12:45  |   
| Bob  | {Chah:[waw,wew,wow]}     | 1-May-2014 09:15:45  |   
==========================================================

现在,给定两个日期时间,我需要在这些日期时间之间为每个人抓一个日志(该时间内的任何日志都会这样做,但最好是在这两个日期时间内最早的日志)。

以下是我尝试过的查询,但仍需要很长时间

select * 
from ( select Name, 
              Log, 
              rank() over (partition by Name order by Date asc) ranks 
        from Table ) alias 
 where ranks = 1

4 个答案:

答案 0 :(得分:1)

您必须使用BETWEEN

   SELECT * 
        FROM ( 
               SELECT Name, Log,
                      rank() OVER (partition by Name ORDER by Date ASC) ranks
                      FROM Table 
                      WHERE Date BETWEEN '2012-04-01 02:00:00′ AND '2012-04-20 02:00:00′
             ) alias 

            WHERE ranks = 1;

您可能要在用于加速查询执行的字段上创建INDEX

答案 1 :(得分:0)

试试这个

SELECT    *
FROM      [YourTable]
WHERE     [YourDate] BETWEEN '08-15-2011 02:00:00' AND '08-16-2011 02:00:00'

答案 2 :(得分:0)

您应该使用BETWEEN条件但在子查询内部

   select * 
    from ( select Name, 
                  Log, 
                  rank() over (partition by Name order by Date asc) ranks 
            from Table 
            WHERE Date BETWEEN @DateBegin AND @DateEnd     
    ) alias 
     where ranks = 1

要更快地运行它,您必须在NameDate字段

上创建索引

答案 3 :(得分:0)

根据您提供的信息,我给出了一个通用示例:

SELECT    *
FROM      [YourTable]
WHERE     [Your Date] BETWEEN '1-May-2013 02:00:00' AND '2-May-2013 02:00:00'
ORDER BY [yourDate] DESC