我不确定哪里出错了,但似乎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
答案 0 :(得分:0)
您需要告诉SQL Server哪些行要包含在窗口中,默认情况下这些功能将是“无限制的预先行和当前行之间的范围”或简写为“ROWS UNBOUNDED PRECEDING”,意味着包括所有行窗口的开始直到当前行。所以知道这一点,以下将会产生你期望的东西。
select a,b,c,
FIRST_VALUE(c) over (partition by a, b order by c asc
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as first_date,
LAST_VALUE(c) over (partition by a, b order by c asc
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as last_date,
row_number() over (partition by a, b order by c asc) as rn
from #temp
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