2016-04-21 8 views
1

Ich habe eine Tabelle im folgenden Format.SQL Self Beitritt Abfrage

Id Orig_Id Type 
11 1111 Internal 
12 1111 Internal 
13 1111 Internal 
14 1112 External 
15 1112 Internal 

Ich möchte alle Orig_Id, die "nur" den Typ als Intern hat. Die Abfrage sollte 1111.

Antwort

3

Return-HAVING:

SELECT Id 
FROM tbl 
GROUP BY Orig_Id 
HAVING 
    SUM(CASE WHEN Type <> 'Internal' THEN 1 ELSE 0 END) = 0 
    AND SUM(CASE WHEN Type = 'Internal' THEN 1 ELSE 0 END) > 0 

Die erste Bedingung stellt sicher, dass die Orig_Id keine Zeilen mit Type = Internal hat. Der zweite stellt sicher, dass es mindestens eine Internal hat.

ONLINE DEMO

1

Nur um zu überprüfen, ob es nur eine Type und die einzige ist, ist 'Internal'

SELECT Orig_Id 
FROM (VALUES (11,1111,'Internal'), 
    (12,1111,'Internal'), 
    (13,1111,'Internal'), 
    (14,1112,'External'), 
    (15,1112,'Internal')) AS T(Id ,Orig_Id, Type) 
GROUP BY Orig_Id 
HAVING 
    -- There is one 
    COUNT(DISTINCT Type) = 1 
    -- and only one internal 
    AND MIN(Type) = 'Internal' 
0

Ich nehme an, dass ich Sie nicht richtig

SELECT DISTINCT Orig_Id FROM YOUR_TABLE WHERE Type='Internal' 
verstehen