我有两个表的学生和班级费用,我想获得报告以查看学生是否支付了费用。
我尝试了这个mysql查询,这是我真正想要的,但是月份和年份也存在问题,即时消息也变成了空列。
这是我尝试过的查询
SELECT student.stu_name, SUM(IF(MONTH(fees.date) = 1, fees.amt, 0)) AS Jan, SUM(IF(MONTH(fees.date) = 2, fees.amt, 0)) AS Feb, SUM(IF(MONTH(fees.date) = 3, fees.amt, 0)) AS Mar, SUM(IF(MONTH(fees.date) = 4, fees.amt, 0)) AS Apr, SUM(IF(MONTH(fees.date) = 5, fees.amt, 0)) AS May, SUM(IF(MONTH(fees.date) = 6, fees.amt, 0)) AS Jun, SUM(IF(MONTH(fees.date) = 7, fees.amt, 0)) AS Jul, SUM(IF(MONTH(fees.date) = 8, fees.amt, 0)) AS Aug, SUM(IF(MONTH(fees.date) = 9, fees.amt, 0)) AS Sep, SUM(IF(MONTH(fees.date) = 10, fees.amt, 0)) AS Oct, SUM(IF(MONTH(fees.date) = 11, fees.amt, 0)) AS Nov, SUM(IF(MONTH(fees.date) = 12, fees.amt, 0)) AS Dece, SUM(fees.amt) AS Total, (28000-(SUM(fees.amt))) AS Balance FROM `fees` INNER JOIN student ON fees.stu_id = student.id GROUP BY student.stu_id
This is the result i'm getting
如果我在两年内添加数据,将会出现问题。
I want to get table like this (orders by month years)
我已经研究了好几个星期,但是我找不到任何解决方案。我感谢您能为此提供帮助。
答案 0 :(得分:0)
这个答案可能为时已晚,但是我建议使用第三张表feedsTotals来设置每年的feed总数。像这样:
create table feesTotals (
id INT NOT NULL AUTO_INCREMENT,
year INT,
total DECIMAL(13,2),
PRIMARY KEY (id)
);
INSERT INTO feesTotals(year,total)
VALUES (2018, 28000.00) , (2019, 29000.00);
比您可以像这样进行查询:
SELECT
student.stu_name,
feesTotals.year,
SUM(IF(MONTH(fees.date) = 1, fees.amt, 0)) AS Jan,
SUM(IF(MONTH(fees.date) = 2, fees.amt, 0)) AS Feb,
SUM(IF(MONTH(fees.date) = 3, fees.amt, 0)) AS Mar,
SUM(IF(MONTH(fees.date) = 4, fees.amt, 0)) AS Apr,
SUM(IF(MONTH(fees.date) = 5, fees.amt, 0)) AS May,
SUM(IF(MONTH(fees.date) = 6, fees.amt, 0)) AS Jun,
SUM(IF(MONTH(fees.date) = 7, fees.amt, 0)) AS Jul,
SUM(IF(MONTH(fees.date) = 8, fees.amt, 0)) AS Aug,
SUM(IF(MONTH(fees.date) = 9, fees.amt, 0)) AS Sep,
SUM(IF(MONTH(fees.date) = 10, fees.amt, 0)) AS Oct,
SUM(IF(MONTH(fees.date) = 11, fees.amt, 0)) AS Nov,
SUM(IF(MONTH(fees.date) = 12, fees.amt, 0)) AS Dece,
feesTotals.total AS Total,
(feesTotals.total-(SUM(IFNULL(fees.amt,0)))) AS Balance
FROM student CROSS JOIN feesTotals
LEFT JOIN fees ON fees.stu_id = student.id AND YEAR(fees.date) = feesTotals.year
GROUP BY student.stu_name, feesTotals.year, feesTotals.total
请参阅DB Fiddle here上的示例