0

我有一个表学生班级女巫包含学生ID和班级ID

CREATE TABLE [StudentClass]
([StudentId] varchar(20), [ClassId] varchar(20));

我想做的是找到一个学生的所有同学。例如:

student 1 in class 1 
student 1 in class 2
student 2 in class 2 

如果我搜索 student1,我想得到结果:
student1 | student2
我实际得到的是:

student1 | null
student1 | student2

如果我只有第一行:

student 1 in class 1 

预期的结果是:

student1 | null

select distinct s1.StudentId, s2.StudentId 
from StudentClass s1
             left join StudentClass s2 
                     on s1.ClassId = s2.ClassId and 
                        s1.StudentId != s2.StudentId
where s1.StudentId = 'Student1'

谢谢您的帮助

4

2 回答 2

0

尝试使用group by而不是distinct

select s1.StudentId as std1, s2.StudentId as std2
from StudentClass s1
             inner join StudentClass s2 
                     on s1.ClassId = s2.ClassId and 
                        s1.StudentId != s2.StudentId
where s1.StudentId = '1'
group by s1.StudentId, s2.StudentId 

你可以在这里查看

于 2012-08-29T08:03:13.510 回答
0

在您的查询中添加这个

SELECT...
FROM..
WHERE...
      AND s2.StudentId IS NOT NULL    -- <== this condition
于 2012-08-29T08:00:39.060 回答