如何知道laravel查询生成器中总和的随机数序列之间的行?

时间:2018-04-10 06:17:14

标签: laravel sum laravel-query-builder

Name    Sales
John    10
Jennifer15
Stella  20
Sophia  40
Greg    50
Jeff    20

我想制作一个如下所示的总和列表并选择一个数字来选择正确的行

SELECT a1.Name, a1.Sales, SUM(a2.Sales) Running_Total 
FROM Total_Sales a1, Total_Sales a2 
WHERE a1.Sales <= a2.Sales OR (a1.Sales=a2.Sales AND a1.Name = a2.Name) 
GROUP BY a1.Name, a1.Sales 
ORDER BY a1.Sales DESC, a1.Name DESC;

当我将其更改为laravel query-builder

$total_grade=DB::query()
        ->select('a1.id','a1.Sales')
        ->addSelect(DB::raw('SUM(a2.Sales) as running total'))
        ->from('Total_Sales as a1')
              ->leftjoin('Toral_Sales as a2', function($join) {
                    $join->on('a1.id', '=', 'a2.id');
                    })
                ->groupBy('a1.id')
        ->where ('a1.Sales','<=','a2.Sales')
        ->orWhere('a2.id','=','a2.id')
        ->orderBy('a1.id')
        ->get();

我弄错了 SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法错误

无法获取查询结果。

id Name     Sales   Running_Total
1  Greg     50      50
2  Sophia   40      90
3  Stella   20      110
4  Jeff     20      130
5  Jennifer 15      145
6  John     10      155

所以我使用下面的内容来获得总数。

$total_sums=DB::table('adlists')
        ->select('countlast')
        ->get()
        ->sum('countlast');

$a=rand(1,$total_sums);


$sums=DB::table('adlists')
        ->select('countlast')
        ->get()
        ->each(function ($item, $key) 
            { 
                dump('$key='.$key);
                dump('$item->countlast='.$item->countlast);

                $total_item=$total_item+($item->countlast);

                if ( $a  < $total_item) 
                    { return $key.';'.$total_item; } ;
            }); 

我收到了错误

Undefined variable: total_items?   

但是如何让$ a找到合适的行呢? ex $ a = 150 - &gt;右边是id = 3

laravel查询构建器能否使它成为一个代码?

0 个答案:

没有答案