在使用连接的情况下的多个列

时间:2013-03-15 05:36:30

标签: mysql case

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

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

但在CASE中,它仅针对一种类型执行?

2 个答案:

答案 0 :(得分:0)

问题有点不清楚,但我认为你正在寻找小组的声明。

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 r.type when 'A' then @payment else @refund end)+sum(r.amount) as total_amount
FROM payments r
GROUP BY r.type

答案 1 :(得分:0)

如果修复了类型,请认为您需要这样的查询:

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

请参阅小提琴here