来自两个表的总和,并计算来自第三个表的余额[MYSQL]

时间:2019-01-04 18:42:48

标签: mysql sum balance

人a有三列,想对其中两列的值求和,然后将结果与其他表进行比较。

   table_a
item | value |  
  A  |   20  | 
  B  |   30  | 
  A  |   20  | 

   table_b
item | value |  
  A  |   40  | 
  A  |   10  | 
  C  |   20  | 

   table_c
item | value_max |  
  A  |  100      | 
  B  |  100      | 
  C  |  200      | 

我想要实现的结果应如下所示:

item | value_sum |  value_max | balance |
  A  |  90       |    100     |    10   |
  B  |  30       |    100     |    70   |
  C  |  20       |    200     |    180  |

我的代码如下:

  select sum(value) as value_sum,
sum(value) as value_sum, value_max-sum(value) as balance
from (
    select value
    from table_a  LEFT JOIN value_max on table_a.item  = table_c.value_max
    union all
    select value
    from table_b LEFT JOIN value_max  on table_b.item  = table_c.value_max 
)  t LEFT JOIN value_max on item  = table_c.value_max  GROUP by item

但是这里有些问题。请帮忙:)

0 个答案:

没有答案