简体   繁体   中英

Selecting rows from the same table using a reference

I am having a table named tblA.I am having the following set of values.

ID    REF     
---------
1     ASD    
2     null    
3     null    
4     null    
5     FGH     
6     null     

Now I am trying to get the rows 1 to 4(ie the starting row will be the one with value 'ASD' in ref column and last row will be the one previous to the row that has some values in REF column say 'FGH').

I tried with between keyword but I am not getting it right.Any way to this?

Could use the rank method:

select * from(
SELECT @rank :=  IF(@prevVal<>ref or ref is null,@rank, @rank+1) AS rank, 
       id,ref,
@prevVal:=ref
FROM   scores
, 
       (SELECT @rank := 0,@prevVal:=null) r 
order by id) m
where m.rank=1

SQL FIDDLE here.

SELECT ID, REF, 
    (CASE WHEN REF IS NOT NULL THEN @refs := @refs + 1 ELSE @refs END) AS counter
FROM (  SELECT ID, REF
        FROM tblA, (SELECT @refs := 0) AS vars
        WHERE ID >= 1
        ORDER BY ID ASC) AS h
HAVING counter = 1

This should work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM