SQL Server选择最近的记录(稍有不同)

时间:2018-08-24 12:48:12

标签: sql sql-server-2008 greatest-n-per-group

假设我有下表:

ActionDate                  ActionType
------------                ------------
2018-08-02 12:59:56.000     Drill
2018-08-02 13:20:45.000     Hammer
2018-08-02 14:36:02.000     Drill

我想基于ActionDate选择最新的ActionType。使用ROW_NUMBER()OVER语法并根据我的排序方式获取第一条或最后一条记录,这不是问题。但是请考虑以下表格设置:

ActionDate                  ActionType
------------                ------------
2018-08-02 12:59:56.000     Drill
2018-08-02 13:20:45.000     
2018-08-02 14:36:02.000     Drill

在这种情况下,由于列出的唯一动作是Drill,所以我希望最早的动作发生,因为该动作实际上并未更改。有没有办法同时满足这两个要求?

1 个答案:

答案 0 :(得分:1)

您可以将TOP 1 WITH TIESCASE语句一起使用。

select top 1 with ties
    *
from YourTable
order by
    case 
        when (select count(distinct ActionType) from @table) = 1 
        then row_number() over (order by ActionDate asc) 
        else row_number() over (order by ActionDate desc)
    end

或者在子查询中,如果您更喜欢...

select ActionDate, ActionType
from
    (select
        *, 
        RN = case 
                when (select count(distinct ActionType) from @table) = 1 
                then row_number() over (order by ActionDate asc) 
                else row_number() over (order by ActionDate desc)
            end
    from YourTable) x
where RN = 1

假设空白实际上是NULL,在COUNT DISTINCT中将被忽略。如果那是一个空格而不是NULL,那么您需要使用一个额外的CASEIIF或类似的符号来处理它:

select top 1 with ties
    *
from YourTable
order by
    case 
        when (select count(distinct case when ActionType = '' then null else ActionType end) from @table) = 1 
        then row_number() over (order by ActionDate asc) 
        else row_number() over (order by ActionDate desc)
    end