[英]SUM of columns while grouping by other column
So this is the structure of my MySQL table that I wanna work this out with: 这就是我要使用的MySQL表的结构:
ID type category_id amount
12 Expense 3 963.39
13 Expense 5 1200.50
14 Expense 3 444.12
15 Expense 5 1137.56
..............................
Desired output: 所需的输出:
1407,41 (for category_id = 3)
2338,06 (for category_id = 5)
....... (and for other category_id)
What I get now: 我现在得到的是:
1407,41 (only for category_id = 3)
My query does not add or display the sum of other category_id. 我的查询未添加或显示其他category_id的总和。
This is the query I am trying: 这是我正在尝试的查询:
$query = "SELECT SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
$expense_count = mysqli_fetch_array($expense_query);
echo $expense_count[0];
Been stuck with this for the last couple of days. 在过去的几天里一直坚持下去。 Any help is very much appreciated.
很感谢任何形式的帮助。 Thank you!
谢谢!
You're only calling mysqli_fetch_array()
once. 您只调用一次
mysqli_fetch_array()
。 You need to call it in a loop to get all the totals. 您需要循环调用它以获取所有总数。 You should also include the category ID in the
SELECT
list. 您还应该在
SELECT
列表中包括类别ID。
$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($expense_query)) {
echo "{$row['TotalAmount']} (for category_id = {$row['category_id']}<br>\n";
}
The query here works. 这里的查询有效。 It's just that you only select the first result from the $expense_count variable.
仅从$ expense_count变量中选择第一个结果。 $expense_count[1] will return the second category listed, $expense_count[2 will return the third one, ect... Try
echo implode(" <br>", $expense_count);
$ expense_count [1]将返回列出的第二个类别,$ expense_count [2将返回第三个类别,以此类推...尝试
echo implode(" <br>", $expense_count);
Have a nice day. 祝你今天愉快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.