sql - how does first_value and last_value works with range unbounded preceding and current row? -
select empno,deptno,sal,hiredate,extract(year hiredate), last_value(sal) over(partition deptno order extract(year hiredate) ) emp; 7782 10 2450 09-jun-81 1981 5000 7839 10 5000 17-nov-81 1981 5000 7934 10 1300 23-jan-82 1982 1300 7369 20 800 17-dec-80 1980 800 7566 20 2975 02-apr-81 1981 3000 7902 20 3000 03-dec-81 1981 3000 7876 20 1100 23-may-87 1987 3000 7788 20 3000 19-apr-87 1987 3000 7900 30 950 03-dec-81 1981 2850 7654 30 1250 28-sep-81 1981 2850 7521 30 1250 22-feb-81 1981 2850 7844 30 1500 08-sep-81 1981 2850 7499 30 1600 20-feb-81 1981 2850 7698 30 2850 01-may-81 1981 2850 select empno,deptno,sal,hiredate,extract(year hiredate), first_value(sal) over(partition deptno order extract(year hiredate)) emp; 7782 10 2450 09-jun-81 1981 2450 7839 10 5000 17-nov-81 1981 2450 7934 10 1300 23-jan-82 1982 2450 7369 20 800 17-dec-80 1980 800 7566 20 2975 02-apr-81 1981 800 7902 20 3000 03-dec-81 1981 800 7876 20 1100 23-may-87 1987 800 7788 20 3000 19-apr-87 1987 800 7900 30 950 03-dec-81 1981 950 7654 30 1250 28-sep-81 1981 950 7521 30 1250 22-feb-81 1981 950 7844 30 1500 08-sep-81 1981 950 7499 30 1600 20-feb-81 1981 950 7698 30 2850 01-may-81 1981 950
the first_value
function returns first value in ordered set. in above example returns first salary value of each department.
but last_value
not return expected output should return last_value
in ordered set. here last_value()
works differently considering last value respect year(which mentioned in order clause)
why work differently?
if omit windowing clause, defaults range between unbounded preceding , current row
in case of first_value , last_value functions.
that means, each record within partition, starting point of window first record. so, same value rows in first_value functions.
however, end point current row itself, keeps on changing each row. so, value of current row value last_value function. but, if order clause not enough reliably identify order, there tie , rows arbitrarily ordered, in example, department 30.
Comments
Post a Comment