SQL- retrieving distinct ID
I have a table with the following data:
ID NAME ATTRIBUTE CODE
=============================
1 XX MM GC
1 XX ST GC
2 ZZ LL GC
2 ZZ ST GC
3 AA MM PC
I need the ID
, name of from the table which contains either MM
A开发者_运维技巧ttribute or GC
code but not both. Like the query should retrieve the ID
numbers only 2 and 3 but not 1 .
How do I do that?
Select Id, Name
From #t
Where (Attribute = 'MM' Or Code = 'GC')
And Id Not In (Select Id From #t
Where (Attribute = 'MM' And Code = 'GC'))
select distinct T1.ID,
T1.NAME
from T as T1
where (T1.ATTRIBUTE = 'MM' or T1.CODE = 'GC') and
not exists (select *
from T as T2
where T1.ID = T2.ID and
T2.Attribute = 'MM' and
T2.CODE = 'GC')
Result:
ID NAME
2 ZZ
3 AA
Try this:
select distinct ID
from TableName
where (Attribute = 'MM' or Code = 'GC')
and not (Attribute = 'MM' AND Code = 'GC')
Try this:
SELECT ID, NAME
FROM <YOUR-TABLE-NAME>
WHERE
(ATTRIBUTE = 'MM' AND CODE <> 'GC') OR
(ATTRIBUTE <> 'MM' AND CODE = 'GC') ;
select distinct Id, Name from tbl? where (attribute = 'MM' or code = 'GC') and not (attribute = 'MM' and code = 'GC')
(
SELECT ID, NAME FROM TableName WHERE CODE = 'GC'
EXCEPT
SELECT ID, NAME FROM TableName WHERE ATTRIBUTE = 'MM'
)
UNION
(
SELECT ID, NAME FROM TableName WHERE ATTRIBUTE = 'MM'
EXCEPT
SELECT ID, NAME FROM TableName WHERE CODE = 'GC'
)
精彩评论