gpt4 book ai didi

mysql - 如何在mysql查询中得到想要的结果?

转载 作者:行者123 更新时间:2023-11-29 12:53:07 26 4
gpt4 key购买 nike

我使用此查询来获取:来自 tblcustomers 的客户名称每个客户的 tbltransactions 交易金额总和

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

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

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

编辑:min(transactionamount) < 0 给出每个客户迄今为止支付的最大金额

最佳答案

您可以使用条件聚合来做到这一点:

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)

关于mysql - 如何在mysql查询中得到想要的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24450873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com