2

I have following sample data from a table

Id      Dsc
500001  INSURED
500001  THIRD PARTY
500001  THIRD PARTY
500001  THIRD PARTY
500002  INSURED
500002  THIRD PARTY
500003  INSURED
500004  BROKER
500005  CLAIMANT

I wish to extract those Ids for which Dsc is neither 'Insured' nor 'Broker'. Since both columns have repetitive data, I have devised following query for this..

Select Id from table1 where Dsc not in ('Insured', 'Broker')
Except
Select Id from table1 where Dsc in ('Insured', 'Broker')

Is there any alternate way to do this?

Mihai
  • 26,325
  • 7
  • 66
  • 81
KMK
  • 25
  • 4

4 Answers4

6
SELECT id FROM table1 GROUP BY id 
HAVING SUM(CASE WHEN Dsc='Insured' THEN 1 ELSE 0 END)=0
AND SUM(CASE WHEN Dsc='Broker' THEN 1 ELSE 0 END)=0
Mihai
  • 26,325
  • 7
  • 66
  • 81
1

You can write a query as:

SELECT Id FROM (
SELECT Id , SUM(CASE WHEN Dsc IN ('INSURED','BROKER') THEN 1 ELSE 0 END ) AS Condition
FROM @Test
GROUP BY Id
) T 
WHERE Condition = 0

DEMO

Deepshikha
  • 9,896
  • 2
  • 21
  • 21
0

Use subquery for the same:

Select id,dsc from (select id,dsc from table1 group by id, dsc) 
where dsc not in('Insured', 'Broker')
Nikhil Batra
  • 3,118
  • 14
  • 19
-1

Use this code to stop repeating column

Select distinct *from table1 
MathieuF
  • 3,130
  • 5
  • 31
  • 34