2016-07-10 44 views
-2

我有一個表格,我需要的結果只是UserId 11,因爲UserId 12沒有lessonId 103但仍然得到結果。T-SQL:同一列中的類似Id

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

輸出:

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

我需要的結果是這樣的:

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

感謝

回答

2

您可以使用聚集了這一點:

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; 

這將返回有兩個課程ID的用戶。由於WHERE子句,這意味着它們同時具有102和103. IN只是簡化了查詢邏輯。

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