Mysql Group表值并显示其总数

时间:2013-01-26 10:25:41

标签: mysql phpmyadmin

我有一张存放厨房库存的桌子。 :

表的结构:tbl_inv

╔══════════════╦══════════╦══════╗
║ MATERIALNAME ║ QUANTITY ║ UNIT ║
╠══════════════╬══════════╬══════╣
║ chicken      ║        5 ║ kgs  ║
║ cheese       ║       10 ║ kgs  ║
║ chicken      ║       10 ║ pcs  ║
║ cheese       ║       10 ║ kgs  ║
║ chicken      ║       10 ║ kgs  ║
╚══════════════╩══════════╩══════╝

我希望在html页面上显示此输出 -

╔═════════════╦══════════╦══════╗
║MATERIALNAME ║ TOTALSUM ║ UNIT ║
╠═════════════╬══════════╬══════╣
║ cheese      ║       20 ║ kgs  ║
║ chicken     ║       15 ║ kgs  ║
║ chicken     ║       10 ║ pcs  ║
╚═════════════╩══════════╩══════╝

我尝试过跟随SQL,

SELECT materialname, SUM(quantity) totalValue FROM tbl_inv GROUP BY materialname";

我不知道在mysql命令中我应该使用什么才能获得此输出。

2 个答案:

答案 0 :(得分:2)

您基本上按materialNameunit

对它们进行了分组
SELECT  materialName, SUM(quantity) totalSum, unit
FROM    tableName
GROUP   BY materialName, unit

OTHER(S)

答案 1 :(得分:1)

使用排序查询尝试此分组...

SELECT  materialName MATERIALNAME, SUM(quantity) TOTALSUM, unit UNIT
FROM    tableName
GROUP   BY MATERIALNAME, UNIT
ORDER   BY MATERIALNAME