代码之家  ›  专栏  ›  技术社区  ›  Jade

尽管我使用了Distinct,但为什么在执行此SQL语句时单个studentid的值不累加?

  •  0
  • Jade  · 技术社区  · 8 年前

    enter image description here

    我使用了Distinct,这样studid只显示一次,但仍然没有得到预期的输出。

    select distinct s.studid,c.fees as total_fees from Student s join 
    Registration r on s.studid=r.studid join Course c on r.courseid=c.courseid
    group by s.studid,c.fees order by s.studid;
    

    我的输出:

    enter image description here

    预期输出:

    enter image description here

    2 回复  |  直到 8 年前
        1
  •  1
  •   bytepusher    8 年前

    您加入注册。 然而,在它上面调用distinct意味着你只能得到其中一个记录。

    SELECT s.studid, SUM(c.fees) as total_fees FROM student s 
    JOIN registration r ON s.studid = r.studid
    JOIN course c ON r.courseid=c.courseid
    GROUP BY s.studid
    ORDER BY s.studid;
    
        2
  •  1
  •   Mureinik    8 年前

    您通过学生ID和费用的不同组合进行查询,而不是 费用:

    SELECT   s.studid, SUM(c.fees) as total_fees 
    FROM     student s 
    JOIN     registration r ON s.studid = r.studid
    JOIN     course c ON r.courseid=c.courseid
    GROUP BY s.studid
    ORDER BY s.studid ASC