Mysql查询SUM动态金额


Mysql Query SUM dynamic amounts

我需要帮助写一个mysql查询SUM金额在一列,其中另一列的值可能是不同的取决于它所包含的值。这是我的表格的一个例子。

account     type         amount
-------     ----         ------
Dell        Inventory    500.00
Microsoft   Inventory    100.00
Cisco       Inventory    300.00
Dell        Inventory    400.00
Webhosting  Service       15.00

这是我到目前为止所做的,它不多,但我想不出一个好的方法来做到这一点。

$result = mysql_query("SELECT * FROM table WHERE type = 'Inventory'");
while($row = mysql_fetch_array($result)){
  Sum the amounts for each account type.  The account types are not fixed, will change regularly
}

正如我上面说的,帐户字段不会固定,所以我不能用帐户名称硬编码我的查询。

那么我想要一份详细列出每个帐户总额的报告。

Dell $900
Microsoft $100
Cisco $300

谢谢你的帮助!

您需要使用聚合函数SUM()来获取每个帐户的总金额。

SELECT  account, SUM(amount) totalAmount
FROM    tableName
WHERE   type = 'inventory'
GROUP   BY account
    MySQL GROUP BY (Aggregate) Functions

我认为您可以使用GROUP BY将您的记录按account分组,因此您可以使用SUM()函数将所有金额相加

SELECT account, SUM(amount) as total
FROM  table
WHERE type = 'inventory'
GROUP BY account
SELECT `account`,sum(`amount`) FROM `table_name` WHERE `type`='Inventory' group by `account`