2016-07-10 7 views
-2

Ich habe eine Tabelle wie diese und ich brauche nur UserId 11, weil UserId 12 keine lessonId 103 ist, aber immer noch Ergebnis.T-SQL: ähnliche ID in derselben Spalte

SELECT * 
FROM LessonList 
WHERE 
    (LessonId = 102 and LessonValue = 1002) 
    or 
    (LessonId = 103 and LessonValue = 1003) 
    or 
    (LessonId = 102 and LessonValue = 1008) 

Ausgang:

Id  UserId  LessonId  LessonValue 
1  11   102   1002 
2  11   103   1003 
3  12   102   1008 

ich so führen müssen:

Id  UserId  LessonId  LessonValue 
1  11   102   1002 
2  11   103   1003 

Dank

Antwort

2

Sie Aggregation für diese verwenden:

SELECT userid 
FROM LessonList 
WHERE (LessonId = 102 and LessonValue IN (1002, 1008)) or 
     (LessonId = 103 and LessonValue = 1003) 
GROUP BY userid 
HAVING COUNT(DISTINCT LessonId) = 2; 

Dies wird Benutzer zurückgeben, die zwei Unterrichts-IDs haben. Aufgrund der WHERE-Klausel bedeutet dies, dass sie beide 102 und 103 haben. Die IN vereinfacht nur die Abfragelogik.

0
SELECT * 
FROM LessonList 
WHERE 
    (LessonId = 102 and LessonValue = 1002) 
    or 
    (LessonId = 103 and LessonValue = 1003) 
    and lessonvalue<>1008 
Verwandte Themen