Id name type
-------------------
1 A coach
1 B coach
1 C client
1 D client
2 E coach
2 F client
2 G client
I want to write a query to find ids having coach more than once but the output should contain rows with value client as well irrespective of its count.
I tried using a subquery but I'm not able to get the desired result.
Tried subquery and also tried to specify value as coach but in that case not getting rows having client values.
I want id having coach more than once along with client if any
A conditional sum() over()
may be a good fit here.
Example
Declare @YourTable Table ([Id] int,[name] varchar(50),[type] varchar(50))
Insert Into @YourTable Values
(1,'A','coach')
,(1,'B','coach')
,(1,'C','client')
,(1,'D','client')
,(2,'E','coach')
,(2,'F','client')
,(2,'G','client')
;with cte as (
Select *
,Coaches = sum( case when [type]='Coach' then 1 end) over (partition by ID)
From @YourTable
)
Select * from cte where Coaches>1
Results
Id name type Coaches
1 A coach 2
1 B coach 2
1 C client 2
1 D client 2
Or another approach
Select A.*
From @YourTable A
Join ( Select id from @YourTable where [type]='Coach' group by id having count(*)>1 ) B
on A.ID=B.ID
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.