+----------------+
| Tables_in_test |
+----------------+
| contribution |
| expectedamount |
| registration |
+----------------+
registration table
+----+--------+-------------+
| id | reg_no | fullname |
+----+--------+-------------+
| 1 | TTI001 | JOHN JAMES |
| 2 | TTI002 | DAVID CERES |
| 3 | TTI003 | JOYCE LEE |
| 4 | TTI004 | JOEL MARTIN |
+----+--------+-------------+
espectedamount
+----+--------+---------+---------+---------+
| id | reg_no | number1 | number2 | number3 |
+----+--------+---------+---------+---------+
| 1 | TTI001 | 500 | 500 | 500 |
| 2 | TTI002 | 500 | 500 | 500 |
| 3 | TTI003 | 500 | 500 | 500 |
| 4 | TTI004 | 500 | 500 | 500 |
| 5 | TTI001 | 400 | 400 | 400 |
| 6 | TTI001 | 1000 | 1000 | 1000 |
| 7 | TTI002 | 1000 | 1000 | 1000 |
| 8 | TTI003 | 1000 | 1000 | 1000 |
| 9 | TTI004 | 1000 | 1000 | 1000 |
+----+--------+---------+---------+---------+
contribution table
+----+--------+---------+---------+---------+
| id | reg_no | number1 | number2 | number3 |
+----+--------+---------+---------+---------+
| 1 | TTI001 | 200 | 400 | 600 |
| 2 | TTI002 | 100 | 50 | 250 |
| 3 | TTI001 | 100 | 400 | 400 |
| 4 | TTI002 | 300 | 400 | 600 |
| 5 | TTI003 | 300 | 100 | 50 |
| 6 | TTI004 | 50 | 60 | 40 |
| 7 | TTI004 | 500 | 300 | 400 |
+----+--------+---------+---------+---------+
我创建了以下查询来联接表registration、expectedamaunt和contribution,其中我想从sum contribution表中减去sum form amount表,但得到的结果是错误的
select registration.reg_no
,registration.fullname
,sum(expectedamount.number1-contribution.number1) as contribution1
,sum(expectedamount.number2-contribution.number2) as contribution2
,sum(expectedamount.number3-contribution.number3) as contribution3
FROM registration
INNER JOIN expectedamount ON registration.reg_no = expectedamount.reg_no
INNER JOIN contribution ON expectedamount.reg_no = contribution.reg_no
GROUP BY reg_no;
+--------+-------------+---------------+---------------+---------------+
| reg_no | fullname | contribution1 | contribution2 | contribution3 |
+--------+-------------+---------------+---------------+---------------+
| TTI001 | JOHN JAMES | 700 | 200 | 0 |
| TTI002 | DAVID CERES | 600 | 550 | 150 |
| TTI003 | JOYCE LEE | 200 | 400 | 450 |
| TTI004 | JOEL MARTIN | 450 | 640 | 560 |
+--------+-------------+---------------+---------------+---------------+
预期结果
+-------+---------------+---------------+------------------+--------------+
|reg_no | fullname | contribution1 | contribution2 | contribution3|
+-------+---------------+---------------+------------------+--------------+
|TTI001 | JOHN JAMES | 1600 | 1100 | 900 |
|TTI002 | DAVID CERES | 1000 | 950 | 550 |
|TTI003 | JOYCE LEE | 1200 | 1400 | 1450 |
|TTI004 | JOEL MARTIN | 950 | 1140 | 1060 |
+-------+---------------+---------------+------------------+--------------+
好心人帮忙。
1条答案
按热度按时间km0tfn4u1#
我想你需要这个-