My question is, if I can use LAG and LEAD, using a condition in the query, for example:
I have the zip column ..
I want to get the value of the next line, and the value of the previous line in that same column. I'm working with C # and SQL Server 2012 .. but making a list in C # with all results is impractical, it's almost 600,000 records.
I tested LAG and LEAD
SELECT
LAG(cid_nucep) OVER (ORDER BY cid_nomec) CidadeAnte,
cid_nucep AS CidadeAtual,
LEAD(cid_nucep) OVER (ORDER BY cid_nomec) ProxCidade
FROM bcadcida
GO
Return was close to what I need:
NULL 87365000 68912350 87365000 68912350 48320000 68912350 48320000 74423970
However, if I use a condition:
SELECT
LAG(cid_nucep) OVER (ORDER BY cid_nomec) CidadeAnte,
cid_nucep AS CidadeAtual,
LEAD(cid_nucep) OVER (ORDER BY cid_nomec) ProxCidade
FROM bcadcida where cid_nucep = 77777777
GO
The result is flawed.
NULL 77777777 NULL
How can I get the value of cid_nucep, the previous line, and the next line?