我有一张表Students(StudentID, classes, school, advisor)
,我需要找到一对学生,这些学生将完全同一组课程。
例如,在表格中:
我会有一个输出:
S3678和S8978
因为他们都使用相同数量的类(2)和类,法语和逻辑。
答案 0 :(得分:0)
使用T-SQL(初始答案是不知道OP正在使用的DBMS ......):
我会用common table expression来解决这个问题:
;WITH cte AS (
SELECT StudentID, COUNT(Classes) numOfClassesTaken,
STUFF((SELECT DISTINCT ', ' + Classes
FROM Students s2
WHERE s2.StudentID = s1.StudentID
ORDER BY ', ' + Classes
FOR XML PATH('')), 1, 2, '') as ClassList
FROM Students s1
GROUP BY StudentID)
, matchingClasses AS (
SELECT numOfClassesTaken, ClassList
FROM cte
GROUP BY numOfClassesTaken, ClassList
HAVING COUNT(*) > 1)
SELECT t1.StudentID, t1.ClassList
FROM cte t1
INNER JOIN matchingClasses t2 ON t1.numOfClassesTaken = t2.numOfClassesTaken AND t1.ClassList = t2.ClassList
答案 1 :(得分:0)
select t1.studentid from (select studentid, array_agg(classes) as classes_set from (select studentid, classes from students order by studentid, classes) as st1 group by studentid) t1 join (select studentid, array_agg(classes) as classes_set from (select studentid, classes from students order by studentid, classes) as st2 group by studentid) t2 on t1.classes_set=t2.classes_set and t1.studentid <> t2.studentid Result: studentid S8978 S3678