4

这是我的 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
4

2 回答 2

4

我假设在您的示例输出余额的最后一行应该是 -5000,而不是 5000,对吗?

SELECT *, purchase - sale AS balance FROM (
  SELECT
    assetid,
    sum(if(fromtype='bank', amount, 0)) AS purchase,
    sum(if(fromtype='asset', amount, 0)) AS sale
  FROM foo f1
  GROUP BY assetid
) f2

在内部查询中,首先我们将 fromtype 为银行的金额相加,否则为 0,反之亦然 fromtype = assets。当然,整个事情都按assetid分组。

然后在外部查询中,我们从内部查询中选择所有内容,并构建差异(这在内部查询中是直接不可能的,因为别名列名不能直接在那里获得)。瞧!

在此处查看实际操作:http ://sqlfiddle.com/#!2/05652/2

于 2013-08-30T13:55:14.797 回答
1

我假设您的意思是购买-销售=余额,并且您希望在最后一行出现 -5000

    CREATE TABLE bla 
    (
      id int AUTO_INCREMENT,
      AssetId int,
      FromType varchar(255),
      ToType varchar(255),
      Ammount int,
      PRIMARY KEY(id)
    ) ENGINE = MyISAM;

    INSERT INTO bla(AssetId,FromType,ToType,Ammount) VALUES
    (1,'Bank','Asset',10000),
    (2,'Bank','Asset',5000),
    (2,'Asset','Bank',4000),
    (3,'Asset','Bank',3000),
    (3,'Asset','Bank',2000);



    SELECT 
      a.AssetId,a.Purchase as Purchase,a.Sale, a.Purchase-a.Sale as Balance
    FROM (
    SELECT a.AssetId,
      (SELECT IFNULL(SUM(b.Ammount),0) FROM bla as b
       WHERE b.AssetId=a.AssetId AND FromType='Bank' AND ToType='Asset') as Purchase,
      (SELECT IFNULL(SUM(b.Ammount),0) FROM bla as b
       WHERE b.AssetId=a.AssetId AND FromType='Asset' AND ToType='Bank') as Sale   
    FROM bla as a
    Group By a.AssetId) as a;
于 2013-08-30T14:02:46.523 回答