2016-07-10 8 views
-2

私はそのようなテーブルを持っていますが、UserId 12はlessonId 103ではありませんが、まだ結果が得られているので、結果はUserId 11だけです。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; 

これは、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 
関連する問題