查询日期之间和之前的行

时间:2014-11-21 18:32:58

标签: sql date sql-server-2012

我有以下表格:

create table MyTable (
    Id int Primary Key Identity,
    UserId int not null,
    StartUnixTime int not null,
    StopUnixTime int not null
)

我需要查询开始和结束时间之间的所有行,以及具有最高StartUnixTime(对于每个UserId)的行,该行小于多个UserIds的给定开始日期。

Currentyl我这样做:

select
    *
from MyTable
where UserId in (select Id from @users)
and (StartUnixTime between @start and @end)

union all

select
    *
from MyTable
where UserId in (select Id from @users)
and StartUnixTime < @start
and StartUnixTime in (
    select
        max(StartUnixTime)
    from MyTable as mt
    where mt.UserId in (select Id from @users)
    and mt.StartUnixTime < @start
    group by mt.UserId
)

是否有更高效的方法来执行此查询?也许没有工会?

1 个答案:

答案 0 :(得分:0)

加入@users表变量并使用“row_number()where = 1”应该更快,以便为每个UserId选择最高记录...

select
    t.Id,
    t.UserId,
    t.StartUnixTime,
    t.StopUnixTime
from MyTable t inner join @users u on t.UserId = u.Id
where t.StartUnixTime between @start and @end

union all

select
    Id,
    UserId,
    StartUnixTime,
    StopUnixTime
from (
    select
        t.*,
        topStart = row_number() over(partition by t.UserId order by t.StartUnixTime desc)
    from MyTable t inner join @users u on t.UserId = u.Id
    where t.StartUnixTime < @start
) tt
where
    topStart = 1