【问题标题】:SQL Select sum price from two tables with two conditions on one syntaxSQL 从具有两个条件的两个表中以一种语法选择总和价格
【发布时间】:2016-11-29 08:05:20
【问题描述】:

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

P/s:我附上数据图片:

【问题讨论】:

标签: mysql sql select syntax sum


【解决方案1】:

有几种方法可以做到这一点。恕我直言,最优雅的方法是根据 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 中不需要大小写 end
  • @jarlh 这是必需的。那是 total_debit 中的一个愚蠢的错字,然后被复制和窃听到 total_credit。感谢您的关注!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多