这是我的 MySQL 表布局
+----+---------+----------+---------+-------+
| id | AssetId | FromType | ToType | Amount |
+----+---------+----------+---------+-------+
| 1 | 1 | Bank | Asset | 10000 |
+----+---------+----------+---------+-------+
| 2 | 2 | Bank | Asset | 5000 |
+----+---------+----------+---------+-------+
| 3 | 2 | Asset | Bank | 4000 |
+----+---------+----------+---------+-------+
| 4 | 3 | Asset | Bank | 3000 |
+----+---------+----------+---------+-------+
| 5 | 3 | Asset | Bank | 2000 |
+----+---------+----------+---------+-------+
购买的资产是 FromType 'Bank' 到 ToType 'Asset'。
出售资产是签证。
如何显示如下所示的表格。
+---------+----------+-----------+---------+
| AssetId | Purchase | Sale | Balance |
+---------+----------+-----------+---------+
| 1 | 10000 | 0 | 10000 |
+---------+----------+-----------+---------+
| 2 | 5000 | 4000 | 1000 |
+---------+----------+-----------+---------+
| 3 | 0 | 5000 | 5000 |
+---------+----------+-----------+---------+
提前致谢。
我试过这个查询。但它不能正常工作
SELECT id as AssetId, debit, credit, 'Asset' AS tb_name
FROM ( (
SELECT id, SUM( `Amount`) AS debit, '0' AS credit
FROM `erp_assets`
WHERE FromType = 'Asset'
GROUP BY AssetId
) UNION ALL (
SELECT id, SUM( `Amount` ) AS credit, '0' AS debit
FROM `erp_assets`
WHERE ToType = 'Asset'
GROUP BY AssetId
) ) AS tb1