Mysql 在使用联接的情况下使用多个列

Mysql 在使用联接的情况下使用多个列,mysql,case,Mysql,Case,我有一张“付款”和“付款”表。两个表上都有一个连接 Payments: ----------- id type amount values 1 A 10 x 2 B 20 y 2 A 30 z 我正在尝试按id和类型分组。这样我就可以得到如下结果 id type total_amount type1 total_amount(sum) ------------------------------------------

我有一张“付款”和“付款”表。两个表上都有一个连接

Payments:
-----------
id  type  amount values
1    A     10     x
2    B     20     y
2    A     30     z
我正在尝试按id和类型分组。这样我就可以得到如下结果

id   type  total_amount type1 total_amount(sum)
-----------------------------------------------
1     A      10                             
2     A      20           B       30      
我试过以下的问题

select 
case when r.type = 'A' then @payment+sum(r.amount) end  as total_amount,
case when r.type = 'B' then @refund+sum(r.amount) end as total_amount(sum)
from payments r

但如果它只针对一种类型执行?

问题有点不清楚,但我假设您正在查找group by语句

select 
case when r.type = 'A' then @payment+sum(r.amount) end  as total_amount,
case when r.type = 'B' then @refund+sum(r.amount) end as total_amount(sum)
FROM payments r
GROUP BY r.type
对于表中每个不同的r.type值,select语句中都会有带有聚合日期的结果行

select 
case when r.type = 'A' then @payment+sum(r.amount) end  as total_amount,
case when r.type = 'B' then @refund+sum(r.amount) end as total_amount(sum)
FROM payments r
GROUP BY r.type
还有一个不同的建议:

select 
(case r.type when 'A' then @payment else @refund end)+sum(r.amount) as total_amount
FROM payments r
GROUP BY r.type

如果类型是固定的,则认为需要这样的查询:

SELECT
  id,
  'A' as type,
  SUM(CASE WHEN type='A' THEN amount END) sum_typeA,
  'B' as type1,
  SUM(CASE WHEN type='B' THEN amount END) sum_typeB
FROM
  Payments
GROUP BY
  id

请看小提琴。

问题不清楚。请列出您的表。表列为付款。假设我们可以使用联接,问题是第二个表(付款1)在哪里?尝试使用左连接