Mysql sum列根据另一列

时间:2016-01-28 07:41:23

标签: mysql

这是我class MaleIconView: UIView { var maleView = UIView() override init(frame: CGRect) { super.init(frame: frame) self.frame = frame setUpView() } func setUpView(){ maleView.frame = CGRectMake(0, 0, self.bounds.width, self.bounds.height) maleView.alpha = 1 maleView.backgroundColor = UIColor.blackColor() maleView.layer.cornerRadius = 0.5 * maleView.bounds.size.width self.addSubview(maleView) } func hide(){ self.removeFromSuperview() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }

中的表格数据
Mysql

我想要我的结果

t_Id  t_Type  t_Date      t_acd_Id  t_acc_Id  t_Amount  t_Desc  t_u_Id    c_Id  
------  ------  ----------  --------  --------  --------  ------  ------  --------
     1       0  2016-01-26       266        29  400.00                 1         1
     2       0  2016-01-27       266        29  160.00                 1         1
     3       1  2016-01-28        29       266  83.30                  1         1
     4       2  2016-01-27        29       272  400.00                 1         1
     5       0  2016-01-27       266       272  300.00                 1         1
     6       1  2016-01-28       272        22  20.00                  1         1

其中 accout_Id rec_Amount pay_Amount ------ ---------- ---------- 29 483.30 560.00 rec_Amountt_acd_Id的总和,是pay_Amount的总和

如何获得此结果?

我当前的查询 t_acc_Id {t_acd_Id {1}} {t_acc_Id {1}}

,它提供了多行

3 个答案:

答案 0 :(得分:1)

你可以试试这个查询吗?因为我已经手动检查了它。

SELECT t4.t_acd_Id as accout_Id ,sum(t4.t_Amount) as rec_Amount, (SELECT SUM(t_Amount) from table4 WHERE t_acc_Id =t4.t_acd_Id) as pay_Amount FROM `table4` as t4 WHERE t4.t_acd_Id IN (29,266) GROUP BY t4.t_acd_Id

由于

答案 1 :(得分:1)

此查询仅满足上述要求(对于单个帐户)。如果您想获得所有帐户的结果,则需要按帐户对记录进行分组。

试试这个(这是根据你的要求):

SELECT CASE 
         WHEN t_acc_id = 29 THEN t_acc_id 
         WHEN t_acd_id = 29 THEN t_acd_id 
       END      account_id, 
       Sum(CASE 
             WHEN t_acd_id = 29 THEN t_amount 
             ELSE 0 
           END) rec_Amount, 
       Sum(CASE 
             WHEN t_acc_id = 29 THEN t_amount 
             ELSE 0 
           END) pay_Amount 
FROM   tbl_transactions 
WHERE  t_acc_id = 29 
        OR t_acd_id = 29 

答案 2 :(得分:0)

以下查询考虑了给定提示可能仅出现在t_acd_Idt_acc_Id中,而不是两者都出现的可能性。在这种情况下,我们希望进行完全外连接,但MySQL不直接支持这一点。相反,我的答案中的第一个子查询获取所有唯一ID值。然后,对于您想要的每个总计,LEFT JOIN为其他两个子查询。

SELECT t1.accout_Id, t2.rec_Amount, t3.pay_Amount
FROM
(
    SELECT DISTINCT t_acd_Id AS accout_Id FROM tbl_transactions
    UNION
    SELECT DISTINCT t_acc_Id AS accout_Id FROM tbl_transactions
) t1
LEFT JOIN
(
    SELECT t_acd_Id AS accout_Id, SUM(t_acd_Id) AS rec_Amount
    FROM tbl_transactions
    GROUP BY t_acd_Id
) t2
ON t1.accout_Id = t2.accout_Id
LEFT JOIN
(
    SELECT t_acc_Id AS accout_Id, SUM(t_acc_Id) AS pay_Amount
    FROM tbl_transactions
    GROUP BY t_acc_Id
) t3
ON t1.accout_Id = t3.accout_Id

点击以下链接查看正在运行的演示

SQLFiddle