如何在mysql查询中获得所需的结果?

时间:2014-06-27 11:35:41

标签: mysql

我使用此查询来获取: 来自tblcustomers的客户名称 tbltransactions对每个客户的transactionamount总和

select a.customerid, sum(transactionamount) as transactionamount ,b.customername
from tbltransactions a 
join tblcustomers b using (customerid) 
group by a.customerid 
order by b.customername

transactionamount中的col tbltransactions包含客户购买的正值和客户付款的负值。

如何在此查询中获取此表达式 min(transactionamount)<每个客户0

编辑:min(transactionamount)< 0给出了每个客户到目前为止支付的最高金额

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合执行此操作:

select a.customerid, sum(transactionamount) as transactionamount, b.customername,
       min(case when transactionamount < 0 then transactionamount end) as BiggestPayment
from tbltransactions a join
     tblcustomers b
     using (customerid)
group by a.customerid
order by b.customername;

注意,小于0的最小值实际上是最小值而非最大值。

编辑:

在这种情况下,我会使用substring_index() / group_concat()技巧找到最新的付款日期:

substring_index(group_concat((case when transactionamount < 0 then transactionamount end)
                              order by transactiondate desc
                            ), ',', 1)

答案 1 :(得分:0)

你想要这个吗?

select a.customerid, sum(transactionamount) as transactionamount ,b.customername 
from tbltransactions a 
join tblcustomers b using (customerid) 
group by a.customerid 
having max(transactionamount) < 0
order by b.customername

仅对仅付款的客户求和?

祝你好运, 内博伊沙