1

I need to pick pairs of rows from a table depending on values in one column. This is my source table:

EntryID |   Code
-----------------
11      |   40
22      |   100  
23      |   80   
24      |   60   
35      |   90   
46      |   80   
47      |   30   
58      |   80   
69      |   20   
110     |   40   

I need to extract only the rows where the code is 80 and the first row after the code 80. So this is the output I seek:

Code
------
80   
60   
80   
30   
80   
20

I can achieve this using cursors but my actual table has 1 million+ records. So cursors are definitely not an option.

I have so far done this:

declare @currentCode int
declare @rowPtr int
declare @code80row bit
declare @nextRowTaken bit
declare @T1 table (RowNum int, Code int)
declare @Final table (RowNum int, Code int)

set @rowPtr = 1
set @code80row = 0
set @nextRowTaken = 0

insert into @T1 select ROW_NUMBER() over (order by EntryID desc) RowNum, Code from Codes
set @currentCode = (select code from @t1 where RowNum = @rowPtr)
while @currentCode > 0
begin
    if @currentCode = 80
    begin
        set @code80row = 1
        set @nextRowTaken = 0
        insert into @Final(RowNum, Code) values (@rowPtr, @currentCode)
    end
    else if (@code80row = 1 and @nextRowTaken = 0)
    begin
        set @code80row = 0
        set @nextRowTaken = 1
        insert into @Final(RowNum, Code) values (@rowPtr, @currentCode)
    end
    set @rowPtr = @rowPtr + 1
    set @currentCode = (select code from @t1 where RowNum = @rowPtr)
end
select * from @Final

Is there a better way to get this result?

EDIT: Following @Serg's reply below, before he added the very last line, I tried this also.... This may help someone with different needs:

;with cte as (
    select Row_Number() over (order by EntryID) RowNum, entryid, Code from Codes
)
select ft.RowNum, st.RowNum, ft.entryid, st.entryid, ft.Code, st.Code
from cte as ft join cte as st
on ft.code = 80 and ft.RowNum = st.RowNum-1

which gives:

RowNum |RowNum |entryid |entryid |Code |Code
--------------------------------------------
3      |4      |23      |24      |80   |60
6      |7      |46      |47      |80   |30
8      |9      |58      |69      |80   |20

3 Answers 3

3

Yes you can use the lag function to see the prior value of a field.

SELECT * 
FROM (
  SELECT *, LAG(Code) OVER (ORDER BY EntryID) AS LAST_CODE
  FROM tablename 
) AS T
WHERE Code = 80 OR LAST_CODE = 80

Fairly sure you can use it in a where on sql-server but I don't have time to test right now and I know that code will work.

6
  • Nice @JuanCarlosOropeza that is helpful!
    – Hogan
    Jul 22, 2016 at 17:45
  • And yes, you need a sub query, and just realize cant use the windows function in a where Jul 22, 2016 at 17:46
  • @Hogan, I need to execute this in SqlServer2008 and SqlServer2012. Lead and Lag work only in 2012 :(
    – KSK
    Jul 22, 2016 at 17:49
  • 1
    @KSK in cases where you need a query work in different version is better indicate it on the question. Other wise we think you over extend with the tags. Jul 22, 2016 at 17:53
  • just federate from the 2012 server :D
    – Hogan
    Jul 22, 2016 at 20:03
1

If you are on 2008 and no lead/lag

with cte as (
    select rn=ROW_NUMBER() over (order by EntryID desc), EntryID, Code 
    from Codes
)
select t2.*
from cte c1 
cross apply ( 
      select EntryID, Code 
      from cte c2 
      where c1.rn between c2.rn and c2.rn+1
) t2
where c1.Code=80;
5
  • Good eye, didnt saw the 2008 there. But you need add the 80 condition Jul 22, 2016 at 17:49
  • Corrected. Thanks @Juan
    – Serg
    Jul 22, 2016 at 17:56
  • I made a small change to match OP request. Check here rextester.com/MSIG81332 Jul 22, 2016 at 18:10
  • @Juan, your addition is quit resonable. OP hasn't requested order explicitly, but i thing it was really implyed.
    – Serg
    Jul 22, 2016 at 20:11
  • Not only that. If you change demo to older version will return [prev , 80], now return [80, next] as OP sample show Jul 22, 2016 at 20:13
0

This will give you current and next:

SELECT EntryID , 
    Code, 
    LAG(Code, 1,0) OVER (ORDER BY EntryID) AS NextCode 
FROM Codes 
WHERE Code = 80
ORDER BY EntryID


EntryID |   Code | NextCode
---------------------
23      |   80   | 60
46      |   80   | 30
58      |   80   | 20
4
  • 1
    Doesn't LEAD give you next and LAG give you prior?
    – Hogan
    Jul 22, 2016 at 17:41
  • @Jonathan, I need to execute this in SqlServer2008 and SqlServer2012. Lead and Lag work only in 2012 :(
    – KSK
    Jul 22, 2016 at 17:49
  • Why are using a database that is past it's end of life? You need to get off that ASAP. Jul 22, 2016 at 19:33
  • @JonathanAllen we're already living in a zombie apocalypse. The solution was deployed when server 2008 was the best that money could buy.
    – KSK
    Oct 7, 2016 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.