如何在单个查询中获取 MySQL 中所有不同项目的所有总和

How to get all the sum of all the distinct items in MySQL in a single query

如何获得所有不同项目的总和?例如0001 equals 100002 equals 10.

什么可能是对下面提供的示例数据的最佳查询(MySQL 或 Laravel 查询生成器)。

tbl_transactions :

+-------+-----------+-----------+
| id    | item_code | quantity  |
+-------+-----------+-----------+
| 1     | 0001      | 6         |
| 2     | 0001      | 4         |
| 3     | 0002      | 7         |
| 4     | 0002      | 3         |
+-------+-----------+-----------+

对于 MySQL,一个基本的 GROUP BY 查询应该可以在这里工作:

SELECT item_code, SUM(quantity) AS total
FROM tbl_transactions
GROUP BY item_code;

Laravel代码:

$report = DB::table('tbl_transactions')
    ->selectRaw('item_code, SUM(quantity) AS total')
    ->groupBy('item_code')
    ->get();

试试这个 mysql

select item_code, sum(quantity) as sum
from tbl_transactions
group by item_code;

DB::table('tbl_transactions')
            ->distinct('item_code')
            ->count('quantity');

你可以试试这个!!!

$report = DB::table('tbl_transactions')
->select([DB::raw("SUM(quantity) as sum"),'item_code']) 
->groupBy('item_code')
->get();