Thursday, September 5, 2019

How to use FIRST_VALUE() and LAST_VALUE() function

DECLARE @Test_table AS TABLE (
 [id] [int] IDENTITY(1,1) NOT NULL,
 [Department] [nchar](10) NOT NULL,
 [Code] [int] NOT NULL
)


--Insert some test data
insert into @Test_table values('A',111)
insert into @Test_table values('B',29)
insert into @Test_table values('A',11)
insert into @Test_table values('C',258)
insert into @Test_table values('D',333)
insert into @Test_table values('E',15)
insert into @Test_table values('F',449)
insert into @Test_table values('G',419)
insert into @Test_table values('H',555)
insert into @Test_table values('I',524)
insert into @Test_table values('J',698)
insert into @Test_table values('K',715)
insert into @Test_table values('L',799)
insert into @Test_table values('M',139)
insert into @Test_table values('N',219)
insert into @Test_table values('O',869)
insert into @Test_table values('P',767)

SELECT * FROM @Test_table


SELECT id,department,code,
FIRST_VALUE(code) OVER (ORDER BY code) FstValue,    ----// FIRST_VALUE  is 15 for all rows as it is value available on 1st rows
LAST_VALUE(code) OVER (ORDER BY code) LstValue    ---// LAST_VALUE returns last value from the row set
FROM @Test_table
ORDER BY id
OFFSET  0 ROWS
FETCH NEXT 5 ROWS ONLY


SELECT id,department,code,
FIRST_VALUE(code) OVER (ORDER BY code) FstValue,
LAST_VALUE(code) OVER (ORDER BY code ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) LstValue    ---// Max value
FROM @Test_table

---// After Insert one more department insert into @Test_table values('A',11)
----// Now The result set is divided into partitions based on the department, so the FIRST_VALUE is different but the same for each partition,
----// while the LAST_VALUE changes for the last row in that partition

SELECT id,department,code,
FIRST_VALUE(code)  OVER (PARTITION BY department ORDER BY code) FstValue,
LAST_VALUE(code) OVER (PARTITION BY department ORDER BY code) LstValue
FROM @Test_table
ORDER BY department

No comments: