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
 General SQL Server Forums
 New to SQL Server Programming
 where exist condition

Author  Topic 

peace
Constraint Violating Yak Guru

420 Posts

Posted - 2013-12-03 : 02:17:42
I have data as below: select ID,code,go,back from tableA

ID code go back
2 C US UK
2 A UK US
1 A US UK
1 Z UK US
1 C UK US
1 A US UK

I only want to pull out whole ID group which code Z exist.
I tried as below:

select ID,code,go,back from tableA A
where exists
( select ID,go,back
from tableA B with (nolock)
where A.ID = B.ID
and A.code='Z')

but it only appear:

ID code go back
1 Z UK US

How can I appear with the group as well?

ID code go back
1 A US UK
1 Z UK US
1 C UK US
1 A US UK

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2013-12-03 : 02:34:17
[code]
select ID, code, go, back
from tableA A
where exists
(
select ID,go,back
from tableA B with (nolock)
where A.ID = B.ID
and B.code = 'Z'
)
[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-03 : 02:41:33
lots of ways in doing this

--using APPLY
select ID, code, go, back
from tableA A
cross apply(
select 1 AS Occ
from tableA with (nolock)
where A.ID = ID
and code = 'Z'
)B

--using window functions
select ID, code, go, back
from (select *, SUM(CASE WHEN code = 'Z' THEN 1 ELSE 0 END) OVER (PARTITION BY ID) AS Cnt
FROM tableA
)A
where Cnt > 0

--using join
select A.ID, code, go, back
from tableA A
INNER JOIN (SELECT DISTINCT ID
FROM Table
WHERE code = 'Z'
)B
ON B.ID = A.ID


--Using IN operator
select ID,code,go,back from tableA
where ID IN
( select ID
from tableA with (nolock)
where code='Z')


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-03 : 02:42:20
Also read this if you're using NOLOCK

http://visakhm.blogspot.com/2010/02/avoiding-deadlocks-using-new.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -