mysql - 如何使用 GROUP BY 两次但不使用 JOIN 本身?
问题描述
在 MYSQL DB 中,我有 people_table :
------------------------------------------
people_table
------------------------------------------
person_ID(INT) name(VARCHAR(45))
1 A
2 B
3 C
4 D
------------------------------------------
和lend_borrow_money_table
------------------------------------------
lend_borrow_money_table
------------------------------------------
bill(DATE) lender_ID money(INT) borrower_ID
2018-11-1 1 100 2
2018-11-2 2 200 3
2018-11-3 3 300 4
2018-11-30 2 400 3
------------------------------------------
现在我想要这样的选择结果
------------------------------------------
name lend borrow total
A 500 0 500
B 400 500 -100
C 0 600 -600
D 0 300 -300
------------------------------------------
以我的方式,我使用 join select 来分组两次,但我认为这不是最好的解决方案
SELECT Lender.name,Lend.lend,SUM(money) AS borrow
FROM lend_borrow_money_table
INNER JOIN people_table AS Borrower ON people_table.ID = lend_borrow_money_table.borrower_ID
INNER JOIN
(
SELECT SUM(money) as lend
FROM lend_borrow_money_table
WHERE bill<'2018/11/31' AND bill>'2018/11/1'
GROUP BY lender_ID
)AS Lend ON Lend.lender_ID
INNER JOIN people_table AS Lender ON people_table.ID = lend_borrow_money_table.lender_ID
WHERE bill<'2018/12/1' AND bill>'2018/11/1'
GROUP BY borrower_ID
我的问题是如何使用 GROUP BY 两次但不使用 JOIN 本身?
解决方案
你可以试试下面
select a.name,sum(b.money) as lend, sum(c.money) as borrow, sum(b.money)-sum(c.money) as total
from people_table a
left join lend_borrow_money_table b on a.id=b.lender_ID
left join lend_borrow_money_table c on a.id=c.borrower_ID
where bill>'20181101' and bill<'20181201'
group by a.name
推荐阅读
- reactjs - onAuthStateChanged firebase auth 创建用户两次 React Nextjs
- vb.net - Tabcontrol.Pages 来自 GUI 设计器后,如何在 Tabcontrol 上动态添加复选框元素?
- r - R H2O - 损失与时代
- lua - 无法在数组中插入变量
- powershell - Powershell:从列中删除重复条目,仅在 csv 文件的原始单元格中保留第一个唯一值
- android - Android导航抽屉透明bug
- java - 休眠搜索配置
- android - 进度条加载不显示服务器的响应?
- c++ - 如何使用谷歌基准测试自定义界面
- python - 如何在 Tkinter 中定位 TopLevel 窗口?