简体   繁体   English

Laravel查询生成器-总和和总和

[英]Laravel Query Builder - Sum Where and Sum Where

I have a table called stock_movements: 我有一个名为stock_movements的表:

| product_id | type | qty  |
|------------|------|------|
| 1          | A    | 2    |
| 1          | A    | 1    |
| 1          | A    | 7    |
| 1          | B    | -2   |
| 1          | B    | -4   |
| 1          | B    | -1   |
| 2          | A    | 2    | 
| 2          | A    | 1    |
| 2          | A    | 7    | 
| 2          | B    | -3   | 
| 2          | B    | -3   |
| 2          | B    | -1   |

I am trying to create a collection of the products where which have the values of the sum of A and sum of B. 我正在尝试创建一个产品集合,这些产品的值分别为A和B的总和。

ie Group by products, type Sum qty for each type 即按产品分组,为每种类型键入求和数量

The key thing is that it is a collection against the product, which is the bit I am struggling with. 关键是它是针对产品的收藏品,这是我努力奋斗的目标。 Does anyone have any advice? 有人有建议吗?

So far I have got... 到目前为止,我已经...

    return $this->stockMovements()->groupBy('product_id')
        ->selectRaw('sum(qty), product_id')
        ->where('type', $this->type)
        ->get();

But this does not split out for types A and B. 但这不会拆分为类型A和B。

You need a basic pivot query, which would look something like this in Laravel: 您需要一个基本的数据透视查询,在Laravel中如下所示:

return $this->stockMovements()
        ->selectRaw("SUM(CASE WHEN type = 'A' THEN qty ELSE 0 END) AS sum_a, ".
                    "SUM(CASE WHEN type = 'B' THEN qty ELSE 0 END) AS sum_b, product_id")
        ->groupBy('product_id')
        ->get();

I removed the WHERE clause, because your data only seems to have two types, and there isn't much sense in restricting that. 我删除了WHERE子句,因为您的数据似乎只有两种类型,并且对其进行限制没有多大意义。 If you really want the sum of quantity for just A or B, then we can write a much simpler Laravel/MySQL query. 如果您真的只想要A或B的数量总和,那么我们可以编写一个更简单的Laravel / MySQL查询。

Using A Raw Expression 使用原始表达

  $result = DB::table('stock_movements')
                ->select(DB::raw('sum(qty) as sum_qty, type'))
                ->groupBy('type')
                ->get();

Rule of thumb for the use of aggregation functions in the SELECT clause . 在SELECT子句中使用聚合函数的经验法则

If a select block does have a GROUP BY clause, any column specification specified in the SELECT clause must exclusively occur as a parameter of an aggregated function or in the list of columns given in the GROUP BY clause, or in both. 如果选择块确实具有GROUP BY子句,则SELECT子句中指定的任何列规范必须排他地作为聚合函数的参数或在GROUP BY子句中给出的列列表中出现,或在两者中都出现。

For more details : http://www.informit.com/articles/article.aspx?p=664143&seqNum=6 有关更多详细信息: http : //www.informit.com/articles/article.aspx?p= 664143& seqNum=6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM