Select month only from Datetime in Laravel - mysql

I have a trouble in selecting month part only from the datetime. I have a column named payment_date in table transaction. I want to select * from transaction and group by month of payment_date. I have try with this code :
$selectedYearTrx = $connectDB->table('transaction')
->join('payment_channel','transaction.payment_channel_id','=','payment_channel.id')
->select('id','payment_date', 'payment_channel_id','amount',DB::raw('MONTH(payment_date) as monthPayment'))
->whereYear('payment_date', '=', $year)
->where('status','=','S')
->wherein('payment_channel_id', [1,2,3])
->where('currency','=','IDR')
->orderBy('id', 'desc')
->get()
->groupBy('payment_channel_id','id','monthPayment');
But, I'm getting error in monthPayment in group by. The error is call a member function groupby().
Can anyone help me to solve this problem?
Thank you.

You should put ->get() at the end of the code )
$selectedYearTrx = $connectDB->table('transaction')
->join('payment_channel','transaction.payment_channel_id','=','payment_channel.id')
->select('id','payment_date', 'payment_channel_id','amount',DB::raw('MONTH(payment_date) as monthPayment'))
->whereYear('payment_date', '=', $year)
->where('status','=','S')
->wherein('payment_channel_id', [1,2,3])
->where('currency','=','IDR')
->orderBy('id', 'desc')
->get()
->groupBy('payment_channel_id','id','monthPayment');
should be
$selectedYearTrx = $connectDB->table('transaction')
->join('payment_channel','transaction.payment_channel_id','=','payment_channel.id')
->select('id','payment_date', 'payment_channel_id','amount',DB::raw('MONTH(payment_date) as monthPayment'))
->whereYear('payment_date', '=', $year)
->where('status','=','S')
->wherein('payment_channel_id', [1,2,3])
->where('currency','=','IDR')
->orderBy('id', 'desc')
->groupBy('payment_channel_id','id','monthPayment')->get();

Related

Laravel MySQL groupby created_at with date format without time

I have a table column named created_at type datetime.
and I want to use groupby for created_at with date only and without time.
Here's my existing code :
$data = BloodPressureHistory::where('user_id', $id)
->groupBy('created_at')
->orderBy('created_at', 'DESC')
->paginate(7);
Use groupBy(DB::raw()) and DATE_FORMAT like this:
$data = BloodPressureHistory::where('user_id', $id)
->groupBy(DB::raw('DATE_FORMAT(created_at,"%Y-%m-%d")'))
->orderBy('created_at', 'DESC')
->paginate(7);
$data = BloodPressureHistory::where('user_id', $id)
->groupBy(function ($item){
return \Illuminate\Support\Carbon::parse($item->created_at)->format('Y-m-d');
})
->orderBy('created_at', 'DESC')
->paginate(7);

How to get total users average time passed 7 days

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."],";
}

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();

Where date time is?

I have Mysql filed date with datetime format.
How can I do where request comparing only date without time part?
I mean the following:
date = 2016-04-45 11:00:00
When I do request I should get row above:
where("date", "=", "2016-04-45")
$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));
$q->whereDate('created_at', '=', date('Y-m-d'));
with Carbon
$q->whereDate('created_at', '=', Carbon::today()->toDateString());
$q->whereDay('created_at', '=', date('d'));
$q->whereMonth('created_at', '=', date('m'));
$q->whereYear('created_at', '=', date('Y'));
whereRaw('date(created_at) = ?', [Carbon::now()->format('Y-m-d')] )

WhereNotIn Subquery

What i'm trying to achieve is the following:
I want to check if there is a record with the same client_code but with a lower/different campaign id. I'm using a sub-query for now and i tried to do it with a join as well but I couldn't get the logic working
This is what i got now:
$oDB = DB::table('campaigns AS c')
->select(
'c.id AS campaign_id',
'cc.id AS campaign_customer_id'
)
->join('campaign_customers AS cc', 'cc.campaign_id', '=', 'c.id')
->where('c.status', '=', ModelCampaign::STATUS_PLANNED)
->where('c.scheduled', '=', 1)
->whereRaw('c.scheduled_at <= NOW()')
->where('cc.status', '=', ModelCampaignCustomer::STATUS_INVITE_EMAIL_SCHEDULED)
->whereNotIn('cc.client_code', '=', function ($query){
$query ->select(DB::raw(1))
->from('campaign_customers')
->whereRaw('campaign_id', '!=', 'c.id');
})
->where('cc.active', '=', 1)
;
any tips on how to work the logic would be great
You can use the ->toSql(); method to see the SQL so you can refactorize your query.
The whereNotIn probably shouldn't have an = in it
->whereNotIn('cc.client_code', function ($query){
....
edit
Try:
->whereNotIn('cc.client_code', function ($query){
$query->select(DB::raw('client_code'))
->from('campaign_customers')
->whereRaw('campaign_id != c.id');
})
I think the whereRaw should be a single text string or maybe you can use where here (looking at this for reference https://laravel.com/docs/5.2/queries#advanced-where-clauses). Also DB::raw(1) is going to return a 1 for each subquery result but you want an id for the whereNotIn.