Question

Edit - restating my need since two guys with way more rank than me misunderstood my question, so I need to make this better...

I have a table like the below. I need to select all of the rows for the first group of 'sec1' rows where the 'ison' column is 1. So the query should first return the 'bbb' row, but if I set all rows to ison=0 and then make the 'ccc' rows ison=1, then I would get two rows of 'ccc' in the result set. Can anyone help me with my rank/top? Using MSSQL 2008.

create table #grp ( sec1 varchar(4) , sec2 varchar(4) , ison bit )
insert into #grp values ( 'aaa' , '001' , 0 )
insert into #grp values ( 'aaa' , '002' , 0 )
insert into #grp values ( 'bbb' , '001' , 1 )
insert into #grp values ( 'ccc' , '001' , 1 )
insert into #grp values ( 'ccc' , '001' , 1 )

Select * From 
( Select 
    sec1 , 
    sec2 , 
    ison , 
    RANK() Over ( partition by sec1 order by sec1,sec2 ) as rowrank
from #grp
where ison=1
) tmp
where rowrank=1

Thanks.

Was it helpful?

Solution

create table #grp ( sec1 varchar(4) , sec2 varchar(4) , ison bit )
insert into #grp values ( 'aaa' , '001' , 0 )
insert into #grp values ( 'aaa' , '002' , 1 )
insert into #grp values ( 'bbb' , '001' , 1 )
insert into #grp values ( 'ccc' , '001' , 1 )
insert into #grp values ( 'ccc' , '001' , 1 )

SELECT  *
  FROM  #grp
 WHERE  sec1 = (
                    Select TOP(1) sec1
                    From 
                        ( Select 
                                sec1 , 
                                sec2 , 
                                ison , 
                                RANK() Over ( partition by sec1 order by sec1,sec2 ) as rowrank
                           from #grp
                          where ison=1
                        ) tmp
                    where rowrank=1
                    Order by sec1, Sec2
                )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top