【发布时间】:2014-11-21 18:32:58
【问题描述】:
我有下表:
create table MyTable (
Id int Primary Key Identity,
UserId int not null,
StartUnixTime int not null,
StopUnixTime int not null
)
我需要查询开始时间和结束时间之间的所有行,加上 StartUnixTime 最高的行(对于每个 UserId),该行小于多个 UserId 的给定开始日期。
目前我正在这样做:
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
)
是否有更高效的方法来执行此查询?也许没有工会?
【问题讨论】:
标签: sql date sql-server-2012