【问题标题】:Query rows between dates and before查询日期和之前的行
【发布时间】: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


    【解决方案1】:

    加入@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
    

    【讨论】:

    • 谢谢,我明天试试,然后给你汇报
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    相关资源
    最近更新 更多