如何在条件下执行总计数(*)

时间:2018-03-03 19:40:04

标签: php mysql sql laravel laravel-5.5

我正在使用Laravel 5.5并且我想在条件上执行SQL查询count(*) as total - 如果http_response等于0,那么它应该将总值设置为0,而不是当前的1

http_response  created_at           session_id                  website_id

404            2018-03-03 17:20:18  2018-03-03 17:15:40-BaC-2   2
404            2018-03-03 17:20:18  2018-03-03 17:15:40-BaC-2   2
404            2018-03-03 17:20:18  2018-03-03 17:15:40-BaC-2   2
0              2018-02-27 14:21:14  2018-02-27 14:19:32-T6f-2   2
404            2018-02-28 14:21:14  2018-02-28 14:19:32-T6f-2   2

我的Laravel查询的外观(如果确实需要,我可以尝试获取此查询的原始SQL查询等效项):

brokenlink::withTrashed()
                ->whereBetween('created_at', [$range['from'], $range['to']])
                ->orderBy('created_at', 'asc')
                ->where('website_id', $website_id)
                ->select('created_at', DB::raw('count(*) as total')) 
                ->groupBy('session_id')
                ->get();

我得到的结果:

03/03/2018 : 3
27/02/2018 : 1
28/02/2018 : 1

期望的结果:

03/03/2018 : 3
27/02/2018 : 0
28/02/2018 : 1

1 个答案:

答案 0 :(得分:2)

使用case-when

 brokenlink::withTrashed()
 ...
 ->select('created_at', DB::raw('CASE WHEN http_response =0 THEN 0 ELSE count(*) END as total')) 
 ->groupBy('session_id')
 ->get();