mysql 把表的值用来计算,如何从mysql中的两个表计算值

本文介绍了如何使用SQL查询从两个表(Credit和Debit)中计算每个公司的余额。通过JOIN操作结合两个表格,分别求出每个公司的总金额和总支出,然后计算差值以得到余额。提供的查询示例展示了如何实现这一目标。
摘要由CSDN通过智能技术生成

I am having a table in mysql like this

Table1 name: creditDate Company Name Amount

2013-12-11 smevc 500

2013-12-21 smevc 500

2013-12-21 smevc 1000

2013-12-21 smevc 6726

2013-12-21 smevc 8354.40

2013-12-20 smevc 700

2013-12-22 sec 3736

2013-12-23 ccs 3000

Table2 name: debit

Date company_name deb_amt

2013-12-24 smevc 1000

2013-12-22 smevc 2000

2013-12-22 sec 736

2013-12-22 ccs 2000

Now i want to take difference calculation here i.e., Amount - deb_amt

Now

I need a output like

comp_name bal_amt

smevc 14780.40

sec 3000

ccs 1000

What query i need to use to get that output?

Thanks,

Siva

解决方案You can Use JOIN between tables

check this link for more info

http://dev.mysql.com/doc/refman/4.1/en/join.html[^]

Try this:

SELECT C.[Company Name] AS COMPNAME, SUM(C.Amount) AS AMT, SUM(D.DEB_AMT) AS DEBIT, SUM(C.Amount) - SUM(D.DEB_AMT) AS BALANCE

FROM Credit AS C INNER JOIN Debit AS D ON C.[Company Name] = D.[Company Name]

GROUP BY C.[Company Name]

For further information about JOIN's, please see: Visual Representation of SQL Joins[^]

No need join.

SELECT cm.`Company Name` AS comp_name,

((SELECT SUM(Amount) FROM credit c WHERE c.`Company Name` = cm.`Company Name` GROUP BY c.`Company Name`) -

(SELECT SUM(deb_amt) FROM debit d WHERE d.company_name = cm.`Company Name` GROUP BY d.company_name)) AS bal_amt

FROM credit cm GROUP BY cm.`Company Name`

ORDER BY bal_amt DESC

I just remember you are using MySql, it will work now. Try it out at sqlfiddle[^].

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值