I am working on Laravel framework. I have a table named 'traffic', contains data for visited users of my website, as like below:
id browser
1 Firefox
2 Firefox
3 Chrome
4 IE
5 Chrome
Now, I want to get the total number of each browser used in a single query. Here is my current query:
Traffic::selectRaw("count(case when browser = 'IE' then 1 end) as IE")
->selectRaw("count(case when browser = 'Firefox' then 1 end) as Firefox")
->selectRaw("count(case when browser = 'Chrome' then 1 end) as Chrome")
->groupBy('browser')
->first();
Which outputs similar to:
Row 1: IE=0, Firefox=0, Chrome=2
Row 2: IE=0, Firefox=2, Chrome=0
Row 3: IE=1, Firefox=0, Chrome=0
But, I want the result to be similar to:
Row 1: IE=1, Firefox=2, Chrome=2
Remove the GROUP BY
logic to get a table-level summary:
Traffic::selectRaw("COUNT(CASE WHEN browser = 'IE' THEN 1 END) AS IE")
->selectRaw("COUNT(CASE WHEN browser = 'Firefox' THEN 1 END) AS Firefox")
->selectRaw("COUNT(CASE WHEN browser = 'Chrome' THEN 1 END) AS Chrome")
->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.