Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Query Help

Author  Topic 

ssunny
Posting Yak Master

133 Posts

Posted - 2012-08-13 : 16:28:39
Hello Guys,

I am sure this must be a simple one but for somereason I can't seem to get it.

Here's my table structure

table : test

aid aname aflag

1 ny N
2 nj N
3 pa Y
3 pa N
4 ct N
4 ct N
4 ct Y


Result I want:

aid aname aflag

1 ny N
2 nj N
3 pa Y
4 ct Y

Logic:

So if there is multiple records for a given aid like aflag = 'Y' and aflag = 'N' , I want to select the one where aflag = 'Y'

Cheers.


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-13 : 16:44:03
[code]
select aid,aname,aflag
from
(
select row_number() over (partition by aid,aname order by case when afalg='Y' then 1 else 2 end) AS Seq,*
from test
)t
where Seq=1
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

ssunny
Posting Yak Master

133 Posts

Posted - 2012-08-13 : 17:03:30
Works great Visakh. Thank you for always helping out people like me.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-13 : 17:09:42
no problem. you're welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2012-08-13 : 18:31:43
Just an alternative; not sure which might be more performant, if either.[CODE]select sid, aname, MAX(aflag) aflag
from test
group by sid, aname[/CODE]

=================================================
Show me a sane man and I will cure him for you. -Carl Jung, psychiatrist (1875-1961)
Go to Top of Page
   

- Advertisement -