用于查找匹配子集的SQL查询

时间:2018-03-04 01:35:51

标签: mysql sql

我有一张表Students(StudentID, classes, school, advisor),我需要找到一对学生,这些学生将完全同一组课程。

例如,在表格中:

enter image description here

我会有一个输出:

  

S3678和S8978

因为他们都使用相同数量的类(2)和类,法语和逻辑。

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

enter image description here

[DEMO HERE]

答案 1 :(得分:0)

  • 如果在postgre8.4 +中,则使用函数" array_agg"
  • 如果这是在mySql5.6中,则将array_agg()更改为GROUP_CONCAT(类)。
  • 如果问题出现在Oracle中,则将GROUP_CONCAT()更改为COLLECT。
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