我在MySQL中有4个这样的表
第一张桌子:学生
id Name roll final
1 vivek 22222 65000
2 abc 33333 50000
第二张表:折扣
id gst_amount roll
1 5000 22222
2 6500 22222
3 15000 22222
4 6000 33333
第三张表:费用
id amount roll
1 15000 22222
2 5000 22222
3 5000 33333
第四张表:pdc
id amount roll
1 9250 22222
2 9250 22222
我想加入所有表,并希望将pdc
和fee
表中的金额和gst_amount
表中的discount
的总和与最后一列的值相加。
我尝试过此查询。
SELECT student.roll, final, SUM(discount.gst_amount) AS total, SUM(fee.amount) AS fee, SUM(pdc.amount) AS pdc
FROM student
LEFT JOIN discount on student.roll = discount.roll
LEFT JOIN fee on fee.roll = student.roll
LEFT JOIN pdc on pdc.roll = student.roll
GROUP BY student.roll
这给了我这个输出。
roll final total fee pdc
22222 65000 106000 120000 110000
33333 50000 6000 5000 NULL
我想要这个输出。
roll final total fee pdc
22222 65000 26000 20000 18500
33333 50000 6000 5000 NULL
答案 0 :(得分:3)
您的原始查询正在计算重复的总和值。
我认为您可以理解将count(1)
列添加到原始查询中。
以下是我的输出。
mysql> SELECT student.roll, count(1) as count
-> FROM student
-> LEFT JOIN discount on student.roll = discount.roll
-> LEFT JOIN fee on fee.roll = student.roll
-> LEFT JOIN pdc on pdc.roll = student.roll
-> GROUP BY student.roll
-> ;
+-------+-------+
| roll | count |
+-------+-------+
| 22222 | 12 |
| 33333 | 1 |
+-------+-------+
2 rows in set (0.00 sec)
基于这些,请按以下sql命令运行。
我认为此sql有一些改进点,但是我现在已经获得了您的预期结果。
我想总输出列中的26000是错误的,我认为26500是正确的。
SELECT
student.roll,
final,
SUM(discount.gst_amount) AS total,
SUM(fee.amount) AS fee,
SUM(pdc.amount) AS pdc
FROM
student
LEFT JOIN
(SELECT
roll, SUM(gst_amount) AS gst_amount
FROM
discount
GROUP BY roll) AS discount ON discount.roll = student.roll
LEFT JOIN
(SELECT
roll, SUM(amount) AS amount
FROM
fee
GROUP BY roll) AS fee ON fee.roll = student.roll
LEFT JOIN
(SELECT
roll, SUM(amount) AS amount
FROM
pdc
GROUP BY roll) AS pdc ON pdc.roll = student.roll
GROUP BY student.roll
答案 1 :(得分:0)
首先,对不起,我没有给您具体答案,但是我并不是最好的。您可以尝试通过子查询来完成。这将获得折扣表中每一卷的gst_amount的总和:
SELECT roll, SUM(gst_amount) AS gst_amount
FROM discount
GROUP BY roll
如果您随后在当前查询中实现它,那么它可能会起作用。