How to get total users average time passed 7 days - mysql

I want to get the per day total users average usage time for passed 7 days i written the the SQL for each users average time it's coming perfectly but i have an u\issues in LARAVEL SQL function please help fix this SQL.
$currentTime = Carbon::today();
$userUsage = DB::table('active_user')
->select(DB::raw('acu_name as name'),
DB::raw('u_fname as fname'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('count(*) as number'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy('acu_name')
->get();

You need to use GROUP BY for this, e.g.:
$userUsage = DB::table('active_user')
->select(DB::raw('acu_name as name'),
DB::raw('u_fname as fname'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('count(*) as number'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy('acu_name', DB::raw('DATE(acu_at)'))
->get();
update
If you just need daily average for all the users, you can remove acu_name from group by, e.g.:
$userUsage = DB::table('active_user')
->select(DB::raw('acu_name as name'),
DB::raw('u_fname as fname'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('count(*) as number'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy(DB::raw('DATE(acu_at)'))
->get();

Correct Answer is
$userUsage = DB::table('active_user')
->select(DB::raw('DATE(acu_at) as date'),
DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
DB::raw('COUNT(DISTINCT `acu_name`) as users'))
->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
->whereDate('acu_at', '<=', $currentTime)
->groupBy(DB::raw('DATE(acu_at)'))
->orderBy(DB::raw('DATE(acu_at)'))
->get();
foreach($userUsage as $usUa)
{
$avegTime = ($usUa->averageTime/$usUa->users);
echo "['".$usUa->date."',".$avegTime."],";
}

Related

How to get row count using laravel fluent query builder

How to get the row count using Laravel fluent query builder
I have attached the query I used to filter other data and also I need to get the row count.
Here is the database Table:-
$results = DB::table('newsfeed_posts')
->select('newsfeed_posts.*', 'users.first_name as posted_user_first_name', 'users.last_name as posted_user_last_name', 'users.profile_image as posted_user_profile_image','proid.profile_image as posted_receiver_profile_image', 'timeline.first_name as post_receiver_first_name', 'timeline.last_name as post_receiver_last_name', 'timeline.office_branch_id as post_receiver_office_id')
->leftJoin('users', 'users.id', 'newsfeed_posts.post_sender_id')
->leftJoin('users as timeline', 'timeline.id', 'newsfeed_posts.post_receiver_id')
->leftJoin('users as proid', 'proid.id', 'newsfeed_posts.post_receiver_id')
->where('newsfeed_posts.deleted_status', '0')
// ->where('newsfeed_posts.post_sender_id', Auth::user()->id)
->where('newsfeed_posts.post_receiver_id', Auth::user()->id)
->groupBy('newsfeed_posts.id')
->orderBy('newsfeed_posts.id', 'DESC')
->get();
return $results;
Using pure Laravel query builder, you may have to issue two separate queries:
$count = DB::table('newsfeed_posts')
->select('newsfeed_posts.*', 'users.first_name as posted_user_first_name', 'users.last_name as posted_user_last_name', 'users.profile_image as posted_user_profile_image','proid.profile_image as posted_receiver_profile_image', 'timeline.first_name as post_receiver_first_name', 'timeline.last_name as post_receiver_last_name', 'timeline.office_branch_id as post_receiver_office_id')
->leftJoin('users', 'users.id', 'newsfeed_posts.post_sender_id')
->leftJoin('users as timeline', 'timeline.id', 'newsfeed_posts.post_receiver_id')
->leftJoin('users as proid', 'proid.id', 'newsfeed_posts.post_receiver_id')
->where('newsfeed_posts.deleted_status', '0')
->where('newsfeed_posts.post_receiver_id', Auth::user()->id)
->groupBy('newsfeed_posts.id')
->count();
Then, use your current query to generate the result set you want.
If you are using MySQL 8+ under the hood, then there is an alternative. We can try using COUNT() as an analytic function, using just a single query:
$results = DB::table('newsfeed_posts')
->selectRaw('COUNT(*) OVER () AS cnt, newsfeed_posts.*', 'users.first_name as posted_user_first_name', 'users.last_name as posted_user_last_name', 'users.profile_image as posted_user_profile_image','proid.profile_image as posted_receiver_profile_image', 'timeline.first_name as post_receiver_first_name', 'timeline.last_name as post_receiver_last_name', 'timeline.office_branch_id as post_receiver_office_id')
->leftJoin('users', 'users.id', 'newsfeed_posts.post_sender_id')
->leftJoin('users as timeline', 'timeline.id', 'newsfeed_posts.post_receiver_id')
->leftJoin('users as proid', 'proid.id', 'newsfeed_posts.post_receiver_id')
->where('newsfeed_posts.deleted_status', '0')
->where('newsfeed_posts.post_receiver_id', Auth::user()->id)
->groupBy('newsfeed_posts.id')
->orderBy('newsfeed_posts.id', 'DESC')
->get();
The count over the entire result set (after GROUP BY aggregation) would then be available using the alias cnt.
If you want to get all the filtered records from database with number of fetched items record. Then you can use firstly use get all results using get() function and on this result you can use ->count() to get all fetched items count.
$result = DB::table('newsfeed_posts')
->select('newsfeed_posts.*', 'users.first_name as posted_user_first_name', 'users.last_name as posted_user_last_name', 'users.profile_image as posted_user_profile_image','proid.profile_image as posted_receiver_profile_image', 'timeline.first_name as post_receiver_first_name', 'timeline.last_name as post_receiver_last_name', 'timeline.office_branch_id as post_receiver_office_id')
->leftJoin('users', 'users.id', 'newsfeed_posts.post_sender_id')
->leftJoin('users as timeline', 'timeline.id', 'newsfeed_posts.post_receiver_id')
->leftJoin('users as proid', 'proid.id', 'newsfeed_posts.post_receiver_id')
->where('newsfeed_posts.deleted_status', '0')
// ->where('newsfeed_posts.post_sender_id', Auth::user()->id)
->where('newsfeed_posts.post_receiver_id', Auth::user()->id)
->groupBy('newsfeed_posts.id')
->orderBy('newsfeed_posts.id', 'DESC')
->get();
return [
'total' => $result->count(),
'result' => $result
];

Laravel count with where on Query Builder with joins

Good day all, I am trying to count all records in a table but only if the table does not contain data in a specific column (deleted_at). It is a join table the table names are companies and employees. I am currently counting the records with a DB::raw but it should only count it if the deleted_at column is null. Please understand that i am a beginner.
public function index()
{
$user = Auth::user()->id;
$companies = DB::table('companies AS c')
->select([
'c.id',
'c.logo',
'c.company_name',
'c.created_at',
'c.sector',
'c.deleted_at',
DB::raw('COUNT(e.id) AS employee_count')
])
->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' )
->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id')
->where('cu.user_id', '=', $user)
->where('c.deleted_at', '=', null)
->groupBy('c.id')
->get();
return view('account.companies.index')
->with('companies', $companies);
}
If you are using Mysql then you could use conditional aggregation
$companies = DB::table('companies AS c')
->select([
'c.id',
'c.logo',
'c.company_name',
'c.created_at',
'c.sector',
'c.deleted_at',
DB::raw('SUM(c.deleted_at IS NULL) AS employee_count')
])
->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' )
->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id')
->where('cu.user_id', '=', $user)
->groupBy('c.id')
->get();
In mysql when an expression is used inside sum(a= b) it will result as a boolean 0/1 so you can get your conditional count using above
Or you could use whereNull() method in your query
->whereNull('c.deleted_at')
Use this code:
$employeeCount = DB::table('employees')
->select('companies.name', DB::raw('count(employees.id) as employee_count'))
->join('companies', 'employees.company','=','companies.id')
->groupBy('companies.id')
->get();

Join 3 table with query builder in laravel

I have a 3 table questions,registrations,ssi_tracks i need to get details from the registraions table by corresponding to other two tables
i need to get details from registrations based on
questions.question_schedul=0 ,ssi_tracks.track_first_status
i have wrote query but it says the column is not found here is my query
$register = DB::table('registrations')
->join('questions', 'registrations.registration_id', '=', 'questions.question_id')
->join('ssi_tracks','registrations.registration_id','=','ssi_tracks.registration_id')
->select('address', 'model', 'chassis', 'delivery_date','ssi_tracks.track_first_status')
->where([["questions.question_schedul", "=", $dropselected] and ['ssi_tracks.track_first_status',0]])
->get();
Try this:
$register = DB::table('registrations as R')
->select('R.address', 'R.model', 'R.chassis', 'R.delivery_date','S.track_first_status')
->join('questions as Q', 'R.registration_id', '=', 'Q.question_id')
->join('ssi_tracks as S','R.registration_id','=','S.registration_id')
->where('Q.question_schedul', '=', $dropselected)
->where('S.track_first_status', '=', 0)
->get();
Make sure you have used the right column here from question table for matching registration id:
->join('questions as Q', 'R.registration_id', '=', 'Q.question_id')
try this query :
$register = DB::table('registrations')
->leftJoin('questions', 'registrations.registration_id', '=', 'questions.question_id')
->leftJoin('ssi_tracks','registrations.registration_id','=','ssi_tracks.registration_id')
->select('registrations.address', 'registrations.model', 'registrations.chassis', 'registrations.delivery_date','ssi_tracks.track_first_status')
->where(['questions.question_schedul'=>$dropselected,'ssi_tracks.track_first_status'=>0])
->get();

checking for multiple values in a single column in laravel 5

So I'm not sure whether I asked the question well. I'm new to laravel and right now I'm building an application where I need to fetch data for a user if certain conditions are met. This is what I'm trying to achieve:
Select from database where userid = $user and userstatus = active or inactive. or pending.
So all rows with the user id($user) and status(active, inactive and pending) will be returned.
I tried doing:
$users = DB::table('users')
->where('status', '=', 'active')
->orwhere('status', '=', 'inactive')
->orwhere('status', '=', 'pending')
->get();
This returned all the data in that particular table. What is the best way to go about this.
You have at least two options for how to do this you can use, including both so you have one for use in this case and one for general usage. Using a function in where creates a new block, so works like adding parentheses to your query
$users = DB::table('users')
->where('id', $user)
->where(function($query) {
$query->where('status', 'active')
->orWhere('status', 'inactive')
->orWhere('status', 'pending');
})->get();
or
$users = DB::table('users')->where('id', $user)->whereIn('status', ['active', 'inactive', 'pending'])->get();
You can do it as:
$users = DB::table('users')
->where('userid', $userid)
->whereIn('status',['active', 'inactive','pending'])
->get();

Laravel : checking the time by whereBetween clause

i want to check if the time entered is existed already in the db or not? here in $dbsum and $dbesum i am doing the sum like if i enter starttime 11:30 then it will give 690 in $dbsum and if i enter endtime 12.30 then it will give 750 in $dbesum. 'c_start' and 'c_end' is the sum that already existed in the database.Now i want to check if $dbsum and $dbesum existed between 'c_start' and 'c_end' or not. my query is like below in controller. but it's not working.
$dbstime = explode(':',$request->input('starttime'));
$dbetime = explode(':',$request->input('endtime'));
$dbstime[0] = $dbstime[0]*60;
$dbetime[0] = $dbetime[0]*60;
$dbsum = array_sum($dbstime);
$dbesum = array_sum($dbetime);
$users=DB::table("bookings")
->select("bookdate")
->where([
['bookdate', '=', $request->input('bookdate')],
['roomname', '=', $request->input('roomname')],
['starttime', '=', $request->input('starttime')],
['endtime', '=', $request->input('endtime')],
->whereBetween('c_start', [$dbsum, $dbesum])
->whereBetween('c_end', [$dbsum, $dbesum])
->get();
$users=DB::table("bookings")
->select("id")
->where('bookdate', '=', $request->input('bookdate'))
->where('roomname', '=', $request->input('roomname'))
->where(function ($query){
$query->where($dbsum, '>', 'c_start');
$query->orWhere($dbsum, '<', 'c_end');
})
->orWhere(function($query){
$query->where($dbesum, '>', 'c_start');
$query->orWhere($dbesum, '<', 'c_end');
})
->get();