在Laravel中,请参阅我编写的代码,但它不正确,因此我需要帮助:
public static function ServiceNo($service,$fltno,$type)
{
$res = DB::table('tbname')
->select(DB::raw('count(distinct(nextSvr)) as svr'))
->where(['fltno'=>$fltno,'mtype'=>$type,'serviceType'=>$service])
->get();
foreach($res as $r){
$cnn = $r->svr;
}
return $cnn;
}
上面的代码将只计算不同的nextsvr,但是,我想要的更好地解释如下:从上面开始,前三个7计为1,接下来的三个序列为1,依此类推,最后服务类型A的总数为9。请在这方面我需要帮助。
答案 0 :(得分:0)
您应该尝试以下示例
$count = DB::table('tablename')->count(DB::raw('DISTINCT name'));
OR
DB::table('tablename')->distinct('name')->count('name');
答案 1 :(得分:0)
尝试一下。
在MySQL中,它将是:
SET @prev := 0;
SELECT sum(col) as distinct_count
FROM (
SELECT *, if(@prev = nextSvr, 0, 1) as col,
@prev := nextSvr
FROM tbname
) x
我认为通过使用变量,您可以找出行之间的变化并相应地增加计数器。因此,如果行发生更改,请添加1。
您可以将其翻译成雄辩的语言并加以使用:
DB::statement(DB::raw('SET @prev := 0'));
$count = DB::select(DB::raw("
SELECT sum(col) as distinct_count
FROM (
SELECT *, if(@prev = nextSvr, 0, 1) as col,
@prev := nextSvr
FROM tbname
) x
"))
答案 2 :(得分:0)
也许您正在寻找类似的东西吗?
public function countServices(Request $request)
{
$counter = 0;
$fltno = '';
$foo = DB::table('bar')
->where([
['fltno', '=', $request->fltno],
['mType', '=', $request->type],
['serviceType', '=', $request->service]
])
->get();
foreach( $foo as $bar )
{
if( $fltno != $bar->fltno )
{
$fltno = $request->fltno;
$counter++;
}
}
return $counter;
}