查询我必须得到老师和学生ID
Select lk.teacherID,lk.studentID from Teacher a inner join student b
on a.classkey = b.classkey
Teacher ID Student ID
123 678
123 876
123 987
456 459
456 789
结束我正在寻找的结果: - 从两列
中查找SQL中的唯一IDUnique IDs
123
678
876
987
456
459
789
答案 0 :(得分:3)
这是你想要的吗?
select t.teacherId
from teachers t
union
select s.studentId
from students s;
编辑:
澄清一下,只需使用cross apply
:
Select distinct id
from Teacher t inner join
student s
on t.classkey = s.classkey cross apply
(values (t.teacherId), (s.studentId)) v(id);
答案 1 :(得分:1)
Select lk.teacherID as UniqueIDs
From(
Select lk.teacherID,lk.studentID from Teacher a inner join student b
on a.classkey = b.classkey)a
GROUP By teacherID
Union all
Select lk.studentID as UniqueIDs From(
Select lk.teacherID,lk.studentID from Teacher a inner join student b
on a.classkey = b.classkey)a
GROUP By studentID
答案 2 :(得分:0)
不需要对数据进行多次传递。
如果OBJECT_ID('tempdb ..#temp','U')不是NULL DROP TABLE #temp;
CREATE TABLE #temp (
Teacher_ID int NOT NULL,
Student_ID INT NOT NULL
);
INSERT #temp (Teacher_ID, Student_ID) VALUES
(123, 678),
(123, 876),
(123, 987),
(456, 459),
(456, 789);
--======================================
SELECT DISTINCT
UniqueID = x.ID
FROM
#temp t
CROSS APPLY ( VALUES (t.Teacher_ID), (t.Student_ID) ) x (ID);
HTH, 杰森