gpt4 book ai didi

mysql - SQL 从两个表中选择总价,使用一种语法有两个条件

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

我有两个关于客户和交易的表。我想获得表交易中至少有一条记录的每个客户的两笔价格。这些价格结果有不同的条件。但我想只用一行来显示所有内容。我该怎么办?

P/s:附上数据图片: enter image description here

最佳答案

有几种方法可以做到这一点。恕我直言,最优雅的方法是根据 customer_id 进行直接连接,然后对 case 表达式求和以处理其他条件

SELECT   a.name, 
SUM(CASE debit WHEN 131 THEN price) AS total_debit,
SUM(CASE credit WHEN 131 THEN price) AS total_credit
FROM customer a
JOIN transactions b ON a.customer.id = b.customer_id
WHERE 131 IN (b.debit, credit)
GROUP BY a.name

关于mysql - SQL 从两个表中选择总价,使用一种语法有两个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40860660/

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