【问题标题】:getting data from multiple tables and applying arithmatic operation on the result从多个表中获取数据并对结果应用算术运算
【发布时间】:2019-10-29 07:44:48
【问题描述】:

我想从两个表中获取数据并对列进行算术运算。

这是我尝试过的:

String sql = "SELECT SUM(S.san_recover-C.amount) as total 
              FROM sanction S 
              LEFT JOIN collection C ON S.client_id = C.client_id 
              WHERE S.client_id=?";

此代码仅在两个表中都有值时有效,但如果两个表中的一个中没有值,则没有结果。

【问题讨论】:

  • 这就是查询的工作方式,因为计算字段直接依赖于两个表?当一列或任一列中不存在数据时,您想要什么。
  • 一栏是给定的金额,第二栏是收取的金额。所以我想要两列的区别
  • 您在 10 月 16 日提出了这个问题,并声称已经解决了这个问题 - 什么不起作用。顺便说一句,我认为我的答案会起作用..
  • @p.Salmon 只有在两个表中都有数据时它才真正起作用。如果其中一个表具有空值,则它不起作用

标签: mysql database join sum left-join


【解决方案1】:
SELECT SUM(S.san_recover - C.amount) as total 
FROM sanction S 
LEFT JOIN collection C ON S.client_id = C.client_id 
WHERE S.client_id = ?

您的查询的问题在于SUM() 函数。当左连接不带回记录时,c.amount 就是NULL。当从某事物中减去 NULL 时,您会得到 NULL 结果,然后该结果会在整个计算中传播,最终您会得到 SUM()NULL 结果。

你可能想要COALESCE(),像这样:

SELECT SUM(S.san_recover - COALESCE(C.amount, 0)) as total 
FROM sanction S 
LEFT JOIN collection C ON S.client_id = C.client_id 
WHERE S.client_id = ?

【讨论】:

  • 感谢先生,这解决了我的问题。它现在也接受空值
  • @gulshankumar:欢迎!如果我的回答正确回答了您的问题,请点击绿色复选标志accept it...谢谢!
  • 还有一个问题。表制裁将 client_id 作为主要但在集合中它的多个条目。所以结果不如预期。请在这方面提供帮助
【解决方案2】:

如果客户端可能存在于一个表中,但没有另一个,则完全连接是合适的,但由于 mysql 没有这样的东西,那么子查询中的联合就可以了

drop table if exists sanctions,collections;

create table sanctions(client_id int, amount int);
create table collections(client_id int, amount int);

insert into  sanctions values 
(1,10),(1,10),(2,10);
insert into  collections values
(1,5),(3,10);

Select sum(Samount - camount)
From
(Select sum(amount) Samount, 0 as camount from sanctions where client_id =3
 Union all
 Select 0,sum(amount) as camount from collections where client_id =3
) s
;

+------------------------+
| sum(Samount - camount) |
+------------------------+
|                    -10 |
+------------------------+
1 row in set (0.00 sec)

如果您想为所有客户执行此操作

Select client_id,sum(Samount - camount) net
From
(Select client_id,sum(amount) Samount, 0 as camount from sanctions group by client_id
 Union all
 Select client_id,0,sum(amount) as camount from collections group by client_id
) s
group by client_id
;
+-----------+------+
| client_id | net  |
+-----------+------+
|         1 |   15 |
|         2 |   10 |
|         3 |  -10 |
+-----------+------+
3 rows in set (0.00 sec)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2021-02-13
    相关资源
    最近更新 更多