This is my MySQL table layout
+----+---------+----------+---------+-------+
| 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 |
+----+---------+----------+---------+-------+
Purchased asset is FromType 'Bank' to ToType 'Asset'.
And Assets Sold is vise visa.
How can I display the table like the one shown below.
+---------+----------+-----------+---------+
| AssetId | Purchase | Sale | Balance |
+---------+----------+-----------+---------+
| 1 | 10000 | 0 | 10000 |
+---------+----------+-----------+---------+
| 2 | 5000 | 4000 | 1000 |
+---------+----------+-----------+---------+
| 3 | 0 | 5000 | 5000 |
+---------+----------+-----------+---------+
Thanks in advance.
I had tried this query. But it is not working properly
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
I assume in the last line of your example output balance should be -5000, not 5000, correct?
In the inner query, first we sum up the amounts where fromtype is bank, otherwise 0, and the same thing the other way around for fromtype = asset. Whole thing gets grouped by assetid, of course.
And then in the outer query we select everything from the inner query, and build the difference (which is not directly possible in the inner query, because the aliased column names are not available directly there). VoilĂ !
See it in action here: http://sqlfiddle.com/#!2/05652/2