SqlServer2012中First_Value函数简单分析

first_value返回结果集中某列第一条数据的值,跟top 1效果一样,比较简单的一个函数

先贴测试用代码

declare @testdata table( 
  id int identity(1,1), 
  department varchar(20), 
  lastname varchar(20), 
  rate float 
) 
insert into @testdata(department,lastname,rate) 
select 'document control','arifin',17.7885 union all 
select 'document control','norred',16.8269 union all 
select 'document control','kharatishvili',16.8269 union all 
select 'information services','chai',10.25 union all 
select 'information services','berge',10.25 union all 
select 'information services','trenary',50.4808 union all 
select 'information services','conroy',39.6635 union all 
select 'information services','ajenstat',38.4615 union all 
select 'information services','wilson',38.4615 union all 
select 'information services','connelly',32.4519 union all 
select 'information services','meyyappan',32.4519 

select * from @testdata

下边使用first_value函数,创建一列新列,返回结果集中第一行的lastname值,这个所谓的第一行受over里的order by影响,看图和代码:

以id正序取

以id倒序取

如果sql脚本中使用了partition分区函数,则first_value返回每个分区内的首条数据值,看演示

这里以department分区,则整个数据集被分成了两部分:information services和document control两块,这时first_value分别返回两块分区内的首条数据值,同样的受order by关键字的影响,

再看一个受order by 影响的例子

与first_value函数同时出现的还有一个,second_value?no,没有这个函数啊,但是有一last_value,怎么函数怎么使用,不打算再单独起一篇文章了,last_value嗯

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐