如何在表中创建两行的总和?

时间:2018-04-19 11:47:55

标签: php mysql

该表的值为

   group_name    group_id    parent_group_id     amount

     One           69             10              1000
     Two           70             11              500
    Three          71             69              700

如果group id = 69与我尝试过的parent_group_id = 69匹配,我需要在amount列中合并值

SUM(CASE WHEN fee_groups.groups_id = fee_groups.parent_fee_groups_id 
            THEN amount 
         ELSE 0 
     END) AS total

但是上面没有为我做任何事情。如果我错了,那么请帮助我实现以下结果,

   group_name    group_id    parent_group_id     amount

     One           69             10              1700
     Two           70             11              500  

此处group_idparent_group_id建立了关系,如果parent_group_idgroup_id中的任何一个匹配,则两者都属于单一组,因此我需要将这两个值相加。

4 个答案:

答案 0 :(得分:0)

根据您想要做的事情,包含group_idparent_group_id对我来说没有意义。你也不解释“71”会发生什么。

select min(group_name) as group_name,
       sum(amount)
from t
group by (case when 69 not in (group_id, parent_group_id) then group_name end);

这将合并共享“69”的组并将其他组分开。

答案 1 :(得分:0)

试试这个解决方案:

SELECT t1.group_name, t1.group_id, t1.parent_group_id, 
      (t1.amount + IFNULL(t2.amount,0)) Amount
FROM Table1 t1
LEFT JOIN Table1 t2 
ON t1.group_id = t2.parent_group_id 
OR t2.group_id = t1.parent_group_id
WHERE t1.group_name < t2.group_name OR t2.group_name IS NULL
GROUP BY t1.group_name, t1.group_id, t1.parent_group_id

<强>输出:

group_name  group_id    parent_group_id   Amount
One         69           10               1700
Two         70           11               500

答案 2 :(得分:0)

试试这个

SELECT 
group_name,group_id,parent_group_id,
(CASE WHEN group_id = 69 THEN 
(amount+(SELECT amount FROM table1 WHERE parent_group_id = 69)) 
ELSE amount END) as new_amount 
FROM Table1 WHERE parent_group_id !=69;

答案 3 :(得分:0)

执行以下执行查询或此链接

sqlfiddle

 select t.group_name,t.group_id,t.parent_group_id,
           (case when t.group_id = t1.parent_group_id then t1.amount + t.amount else t.amount end)
    from t 
    left join t as t1 on t.group_id = t1.parent_group_id
where t.group_id <>71