MYSQL获取汇总列的总数

时间:2019-03-17 12:46:46

标签: mysql sql

在学校示例问题中有这个问题,我必须获得三月份教练和参与者的总薪水(如下所示),然后我必须求和才能获得三月份我想要的所有员工的总薪水添加到“工资总额”列的末尾。

这是我到目前为止所拥有的:

(SELECT Coach.name AS Name, COUNT(*) AS 'Shows Attended In March', 
dailySalary AS 'Daily Salary', sum(dailySalary) AS 'Total Salary' 
FROM Coach, TVShow, CoachInShow 
WHERE monthname(dateOfShow)='March' AND 
Coach.idCoach=CoachInShow.idCoach AND TVShow.idShow = 
CoachInShow.idShow 
GROUP BY Coach.name, Coach.dailySalary)

UNION

(SELECT Participant.name AS Name, COUNT(*) AS 'Shows Attended In 
March', dailySalary AS 'Daily Salary', sum(dailySalary) AS 'Total 
Salary'
FROM Participant, TVShow, Contender, ContenderInShow
WHERE monthname(dateOfShow)='March' AND Participant.idContender = 
Contender.idContender AND Contender.idContender = 
ContenderInShow.idContender AND ContenderInShow.idShow = TVShow.idShow
GROUP BY Participant.name, Participant.dailySalary);

我尝试在整个过程中使用GROUP BY WITH ROLLBACK,但它并不仅仅累加TotalSalary列。我已经花了一段时间了,有点困惑。

我将要粘贴的数据粘贴到这里:https://www.db-fiddle.com/f/gPKVQrZCMkvHUqViAUzCqZ/0 http://sqlfiddle.com/#!9/535f6d/1

1 个答案:

答案 0 :(得分:0)

UNION放入子查询中。在主查询中,将所有计数和薪金总额相加,然后使用WITH ROLLUP获得总计。

dailySalary子句中不需要GROUP BY,因为它在功能上取决于ID。

SELECT name AS Name, SUM(count) AS `Shows Attended in March`, SUM(totalSalary) AS `Total Salary`
FROM (
    SELECT Coach.name, COUNT(*) AS count, SUM(dailySalary) AS totalSalary
    FROM Coach
    JOIN CoachInShow ON Coach.idCoach=CoachInShow.idCoach
    JOIN TVShow ON TVShow.idShow = CoachInShow.idShow 
    WHERE monthname(dateOfShow)='March'
    GROUP BY Coach.idCoach

    UNION

    SELECT Participant.name, COUNT(*) AS count, SUM(dailySalary) AS totalSalary
    FROM Participant
    JOIN Contender ON Participant.idContender = Contender.idContender 
    JOIN ContenderInShow ON Contender.idContender = ContenderInShow.idContender
    JOIN TVShow ON ContenderInShow.idShow = TVShow.idShow
    WHERE monthname(dateOfShow)='March'
    GROUP BY Participant.idParticipant
) AS x
GROUP BY Name
WITH ROLLUP

DEMO