如何查询两个mysql表的一个字段的总和

时间:2017-09-21 06:21:17

标签: mysql sum

我有两个mysql表。 表:账单

id | billtype | amount | advid |   paydate  |adjid |  adjdate   |
 1 | electric | 10000  |  123  | 2017-01-01 | 50   | 2017-01-03 |
 2 |   Water  |  5000  |  124  | 2017-02-01 |  0   | 0000-00-00 |
 3 |   Shirt  |   500  |  125  | 2017-03-01 |  0   | 0000-00-00 |

表:提前

 id | advid | amount | balance | purpose |
 1  | 123   | 50000  |  20000  |   Bill  |
 2  | 124   | 70000  |  10000  |   Bill  |
 3  | 125   | 55000  |  15000  | Uniform |
 4  | 124   | 60000  |  10000  |   Bill  |

我想创建一个下拉菜单,以便选择那些' advance'在表格中没有调整(adjid = 0和adjdate = 0000-00-00):bill和下拉菜单也将包含相同预付ID(advid)的预付总值,如下所示:

<option>Bill-130000</option>
<option>Uniform-55000</option>

由于提前身份124的预付总额为130000(70000 + 60000),所以如果比尔,选项菜单中的预付总额应为130000。但我未能准确计算总推进量:

SELECT sum(a.amount), purpose FROM bill as b, advance as a WHERE b.paydate!='0000-00-00' AND b.adjid!=0 AND a.advid=b.advid GROUP BY a.advid

<option></option>中的总金额未实现。

为此目的的正确查询是什么?

1 个答案:

答案 0 :(得分:2)

你可以尝试

SELECT SUM(a.amount) AS amount, 
       MAX(purpose)  AS purpose 
FROM   advance a 
WHERE  a.advid IN (
               SELECT b.advid 
               FROM   bill b 
               WHERE  b.paydate = '0000-00-00' 
                      AND b.adjid = 0) 
GROUP  BY a.advid