1

I'm trying to solve a seemingly simple problem, but I think i'm tripping over on my understanding of how the EXISTS keyword works. The problem is simple (this is a dumbed down version of the actual problem) - I have a table of students and a table of hobbies. The students table has their student ID and Name. Return only the students that share the same number of hobbies (i.e. those students who have a unique number of hobbies would not be shown)

So the difficulty I run into is working out how to compare the count of hobbies. What I have tried is this.

SELECT sa.studentnum, COUNT(ha.hobbynum)
FROM student sa, hobby ha
WHERE sa.studentnum = ha.studentnum
AND EXISTS (SELECT *
            FROM student sb, hobby hb
            WHERE sb.studentnum = hb.studentnum 
            AND sa.studentnum != sb.studentnum
            HAVING COUNT(ha.hobbynum) = COUNT(hb.hobbynum)
           )
GROUP BY sa.studentnum
ORDER BY sa.studentnum;

So what appears to be happening is that the count of hobbynums is identical each test, resulting in all of the original table being returned, instead of just those that match the same number of hobbies.

4

2 回答 2

2

未经测试,但可能是这样的(如果我正确理解问题):

WITH h AS (
  SELECT studentnum, COUNT(hobbynum) OVER (PARTITION BY studentnum) student_hobby_ct
    FROM hobby)
SELECT studentnum, student_hobby_ct
  FROM h h1 JOIN h h2 ON h1.student_hobby_ct = h2.student_hobby_ct AND
                         h1.studentnum <> h2.studentnum;
于 2013-02-03T02:00:01.217 回答
1

我认为您的查询只会返回至少有其他学生具有相同爱好的学生。但是你不会返回任何关于他们匹配的学生的信息。这是故意的吗?在加入计数之前,我会将这两个查询都视为子查询和聚合。你可以做几件事......这里它返回具有匹配爱好计数的学生数量,但你可以限制 HAVING(COUNT(distinct sb.studentnum) = 0 以获得你的查询似乎返回的结果......

with xx as 
(SELECT sa.studentnum, count(ha.hobbynum) hobbycount
            FROM student sa inner join hobby ha
            on sa.studentnum = ha.studentnum
            group by sa.studentnum
           )
select sa.studentnum, sa.hobbycount, count(distinct sb.studentnum) as matchcount
from
xx sa inner join xx sb on 
    sa.hobbycount = sb.hobbycount
where
    sa.studentnum != sb.studentnum
GROUP by sa.studentnum, sa.hobbycount
ORDER BY sa.studentnum;
于 2013-02-03T02:10:15.843 回答