如何将以下SQL查询转换为Laravel查询?
SELECT roster_date, COUNT(DISTINCT truck_id) AS available_units
FROM truck_rosters
WHERE(truck_rosters.status = 'Active')
并与以下查询合并:
SELECT名单日期,COUNT(DISTINCT truck_id)作为总单位 从truck_rosters GROUP BY roster_date
预期结果:
2019-08-30 | 11 | 3 2019-08-31 | 10 | 4
答案 0 :(得分:0)
对两个计数使用条件聚合:
$rosters = DB::table('truck_rosters')
->select(DB::raw("COUNT(DISTINCT truck_id) AS total_units,
COUNT(CASE WHEN status = 'Active' THEN 1 END) AS active_units, roster_date"))
->groupBy('roster_date')
->get();