2015-02-11 91 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