如何计算小组总数?

时间:2011-12-27 23:41:40

标签: mysql group-by

我有一个查询,它从连接两个表中返回以下内容:

+---------------+-----------------+
| Type          |  Price          |
+---------------+-----------------+
| Music         |  19.99          |
| Music         |   3.99          |
| Music         |  21.55          |
| Toy           |  89.95          |
| Toy           |   3.99          |
+---------------+-----------------+

我的问题是如何按类型对产品进行分组,以便显示每种产品类型的单一产品类型和总价?例如:

Music | 45.53
Toy   | 93.94

等等。

3 个答案:

答案 0 :(得分:7)

SELECT type, SUM(price) FROM table_name GROUP BY (type)

答案 1 :(得分:1)

mysql> select type, round(sum(price),2) sum from storage group by type;
+-------+-------+
| type  | sum   |
+-------+-------+
| Music | 45.53 |
| Toy   | 93.94 |
+-------+-------+
2 rows in set (0.11 sec)

答案 2 :(得分:0)

终于明白了。

// Get the sum
$group = array();
foreach($rows as $r){
  $group[$r->type] = $group[$r->Type] + $r->Price;
}

// Display
foreach($group as $type=>$price){
  echo "Type:".$type." Price: ".$price;
}

原帖在这里:Group results in subgroups