假设我有一个Gigantic表格,使用这种格式从一开始就保存了大量日志:

==========================================================
| 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

最佳答案

您应该使用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字段上创建索引

关于sql - 如何查找两个日期之间的特定记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20854446/

10-16 13:32