我正在尝试通过使用 mysql 中的连接查询来连接表并获取数据

时间:2021-04-14 12:16:49

标签: mysql

我正在尝试添加四个表,如果数据存在,我想添加三个表中的值然后它想添加值否则它想将 0 添加到该值我使用左连接使用它我得到不同的值

MariaDB [kjpuram]> select  centercode, aarrears,medicine, aothers from school_additions;
+------------+----------+----------+---------+
| centercode | aarrears | medicine | aothers |
+------------+----------+----------+---------+
| 107        |        0 |        0 |   13250 |
| 102        |        0 |        0 |  100000 |
| 107        |   100000 |        0 |       0 |
| 107        |    12540 |        0 |       0 |
+------------+----------+----------+---------+
4 rows in set (0.027 sec)

MariaDB [kjpuram]> select sum(net),centercode from school_daily_data group by centercode;
+--------------------+------------+
| sum(net)           | centercode |
+--------------------+------------+
|         556391.968 | 102        |
|          13877.835 | 103        |
| 210642.76699999993 | 107        |
+--------------------+------------

对于 107 中心代码,我想要 323892.767

MariaDB [kjpuram]> select  C.id id,D.centercode centercode,round(sum(D.net),3) amount,COALESCE(L.installment_amt,0) lamount,round(COALESCE((sum(D.net)+COALESCE(sum(A.cartage),0)+COALESCE(sum(A.autofine),0)+COALESCE(sum(A.aarrears),0)+COALESCE(sum(A.aothers),0)+COALESCE(sum(A.commission),0)-COALESCE(sum(A.cattlefeed),0)-COALESCE(sum(A.stores),0)-COALESCE(sum(A.medicine),0)-COALESCE(sum(A.stationary),0)-COALESCE(sum(A.emtcharges),0)-COALESCE(sum(A.seed),0)-COALESCE(sum(A.insurance),0)-COALESCE(sum(A.rarrears),0)-COALESCE(sum(A.rothers),0)-COALESCE(sum(L.installment_amt),0)),0),3) net  from school_center C  join school_daily_data D on C.centre_code = D.centercode and D.date between '2021-03-01' and '2021-03-31' left join school_additions A on C.centre_code = A.centercode and A.date between '2021-03-01' and '2021-03-31' left join school_loanbillsdata L on C.centre_code = L.centercode and L.idate between '2021-03-01' and '2021-03-31' group by D.centercode,A.centercode;
+----+------------+------------+---------+-------------+
| id | centercode | amount     | lamount | net         |
+----+------------+------------+---------+-------------+
| 37 | 102        | 556391.968 |       0 | 6756391.968 |
| 38 | 103        |  13877.835 |       0 |   13877.835 |
| 40 | 107        | 631928.301 |       0 | 4531418.301 |
+----+------------+------------+---------+-------------+
3 rows in set (0.007 sec)

当我使用这个查询时,我得到了这个值

0 个答案:

没有答案