2015-02-11 73 views
1

我不确定哪里出错了,但看起来LAST_VALUE函数没有返回所需的结果。我想要做的是如下SQL Server 2012中的LAST_VALUE函数

Create table #temp(
    a varchar(10), 
    b varchar(10), 
    c datetime 
    ) 

    insert into #temp 
    Values('aa','bbb','2014-10-15 16:39:41.000'), 
    ('aa','bbb','2014-10-16 06:00:04.000') 

    select a,b,c, 
    FIRST_VALUE(c) over (partition by a, b order by c asc) as first_date, 
    LAST_VALUE(c) over (partition by a, b order by c asc) as last_date, 
    row_number() over (partition by a, b order by c asc) as rn 
    from #temp 

我得到的结果如下,它有不同的最后值。

a | b | c | first_date | last_date | rn

aa | bbb | 2014-10-15 16:39:41.000 | 2014-10-15 16:39:41.000 | 2014-10-15 16:39:41.000 | 1

aa | bbb | 2014-10-16 06:00:04.000 | 2014-10-15 16:39:41.000 | 2014-10-16 06:00:04.000 | 2

+3

可能重复[SQL:最后\ _Value()返回错误的结果(但首先\ _Value()工作正常)](http://stackoverflow.com/questions/15388892/sql-last-value-回报 - 错误的结果,而是先价值的作品精细) – 2015-02-11 20:04:14

回答

0

您需要告诉SQL Server要在窗口中包含哪些行,默认情况下这些功能是“无界前和当前行之间的范围”或简写为“ROWS UNBOUNDED PRECEDING”,意思是包含所有行从窗口开始的行直到当前行。所以知道这一点,以下会导致你所期望的。 PS:这给出了相同的结果,但是可读性更强一些,可能更快一些。

select a,b,c, 
    min(c) over (partition by a, b) as first_date, 
    max(c) over (partition by a, b) as last_date, 
    row_number() over (partition by a, b order by c asc) as rn 
from #temp