使用聚合函数时如何返回多行?

时间:2016-12-07 14:43:43

标签: mysql sql

SELECT StudentID, Fname, LName, S_LessonNumber, LessonName, Date, Cost
FROM STUDENT_2
JOIN LESSON ON S_LessonNumber = LessonNumber
NATURAL JOIN STUDENT_1
WHERE StudentID = '1001'

我通过此查询得到的结果表如下,

enter image description here

当尝试显示已支付的总金额以及所使用的课程总数时,使用以下查询,我只能返回一行。

SELECT StudentID, Fname, LName, S_LessonNumber, LessonName, Date,
Cost,COUNT( DISTINCT S_LessonNumber ) , SUM( Cost )
FROM STUDENT_2
JOIN LESSON ON S_LessonNumber = LessonNumber
NATURAL JOIN STUDENT_1
WHERE StudentID = '1001'

enter image description here

有没有办法可以返回所有4行,并重复COUNT(DISTINCT S_LessonNumber)和SUM(Cost)的值。

所需的输出如下:

StudentID FName    LName   S_LessonNumber LessonName Date Cost COUNT SUM
1001      Hannibal Lecter  7              C---       ---  15   4     60 
1001      Hannibal Lecter  6              Wa--       ---  15   4     60 
1001      Hannibal Lecter  5              Tri--      ---  15   4     60 
1001      Hannibal Lecter  1              Cha-       ---  15   4     60 

2 个答案:

答案 0 :(得分:0)

聚合函数将始终返回1行。如果使用子查询不是问题,您可以这样做:

SELECT StudentID, Fname, LName, S_LessonNumber, LessonName, Date, Cost,
  (SELECT COUNT( DISTINCT S_LessonNumber ) FROM STUDENT_2 JOIN LESSON ON S_LessonNumber = LessonNumber NATURAL JOIN STUDENT_1 WHERE StudentID = '1001') AS COUNT,
  (SELECT SUM( Cost ) FROM STUDENT_2 JOIN LESSON ON S_LessonNumber = LessonNumber NATURAL JOIN STUDENT_1 WHERE StudentID = '1001') AS SUM
FROM STUDENT_2
JOIN LESSON ON S_LessonNumber = LessonNumber
NATURAL JOIN STUDENT_1
WHERE StudentID = '1001'

答案 1 :(得分:0)

在此处查看:http://rextester.com/SBUQ82088

create table if not exists fstudents (id int, fname text, lname text);
create table if not exists fstudents2 (student_id int, lesson_number int, lesson_date date, cost int);
create table if not exists flessons (number int, name text);
insert into fstudents values (1001, 'Anibal', 'Lecter');
insert into flessons values (1, 'Cha Cha');
insert into flessons values (2, 'Waltz');
insert into flessons values (3, 'Country');
insert into flessons values (4, 'Triple2');
insert into fstudents2 values (1001, 1, '2016-10-06', 15);
insert into fstudents2 values (1001, 2, '2016-10-07', 15);
insert into fstudents2 values (1001, 3, '2016-10-08', 15);
insert into fstudents2 values (1001, 4, '2016-10-09', 15);

使用子查询计算总和,然后将其加入主查询。

select st2.student_id, st.fname, st.lname, ls.name, st2.lesson_date, st2.cost, agg.courses, agg.total_cost
from fstudents2 st2
    join fstudents st on st2.student_id = st.id
    join flessons ls on st2.lesson_number = ls.number
    join (select st3.student_id, count(st3.lesson_number) courses, sum(st3.cost) total_cost 
          from fstudents2 st3
          group by st3.student_id) agg on agg.student_id = st2.student_id
where
    st2.student_id = 1001;