How to get duplicate records according to name, date range and status exactly? - laravel-5

I am trying to get the duplicate records that match a date range and according to their state field exactly.
I am trying with the following query
$datos = DB::table('especialidades')
->select('id','uuid','nombre','created_at')
->orderBy('nombre')
->whereIn('nombre', function($q){
$q->select('nombre')
->from('especialidades')
->groupBy('nombre')
->havingRaw('COUNT(*) > 1');
})
->where('created_at', '>=', '2022-10-18')
->where('created_at', '<=', '2022-10-20')
->where('estado', 6)
->get();
And it returns the following results
I must show exactly when they are:
The record has duplicates
Duplicate records are on the same date
All duplicate records have the same status.
If it does not exactly meet these 3 conditions, it should not be displayed.
As you will see in the image of the records, those in red
They have duplicates
Some duplicates of the record are in different date ranges, so it should not be displayed.
Some duplicates of the record are in different states, so it should not show it.
The correct result should have been the ones highlighted in green, since they meet the 3 conditions exactly.

Related

Laravel 8- Eloquent order table results in days array

I am trying to assemble a graph of tasks per user/day, but I can't find how to order it easily.
I make the following queries to collect the tasks;
$tasksLastMonth = Task::where('user_id', Auth::user()->id)
->whereMonth('date', Carbon::now()->month)
->with('client')->get();
$tasksLastWeek = Task::where('user_id', Auth::user()->id)
->where('date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
->with('client')->get();
On the other hand, I have two arrays with the days of the week and the month for the Xaxis of graph (are 2 graphs, one for week, and other for month)
$weekDays // [7,8,9,10,11,12,13]
$week // [1,2,3,4,.....,28]
Now, I need two arrays of the same length as the days of the week and month, for the Y axis, containing the number of tasks for each day. For example, if on day 8 there are 5 tasks it would look something like this:
$tasksInWeek = [0,5,0,0,0,0,0];
I also need other arrays for the number of clients for each day, but only the different ones. If one day there are 2 tasks for the same client, I only have to add 1 client that day.
I may be able to do it with just the query, but I can't find a way.
This should work:
$groupedTasks = Task::where('user_id', Auth::user()->id)
->whereMonth('date', Carbon::now()->month)
->with('client')
->get()
->groupBy(function ($item) {
return $item->date->format('Y-m-d');
})
->map(function ($items, $date) {
return $items->unique('user_id');
});
The idea here is to, first, group the elements by the date (instead of using an integer) and then, on each group just keep the distinct users.
You can duplicate almost the same logic to get the data for the weekly chart.

Display result in graph based on combination of year and month selection in laravel

i am display graph of sum of qty datewise it works but now i want to display graph in which sum of qty of month and year combine selection. My date is stored in format 2020-02-14 and i want to display sum of qty of 2020-02 that is from 2019-02 to 2020-09. I tried lot of works. I am getting graph date wise but now i want to year and month combine
For date selection the query as
$get_details=DB::select('SELECT sum(orders_qty) as sum_of_qty,deliver_date FROM `orders` WHERE deliver_date between ? AND ? GROUP BY deliver_date',[$data['start_date'],$data['end_date']]);
For yearand month selection i need query
I tried like this
$data=$req->all();
$results = DB::table('orders')
->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
->groupBy('deliver_date')
->get();
$date[start_year_month]='2019-02' $date[end_year_month]='2019-05' and actual database date='2019-02-14'
plz need query
First, use %Y-%m instead of %y-%m;
Secondly, you are rewrite your field's name, so group by will not using the name that has been rewritten, you need to specify DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")
So the query like this:
$data=$req->all();
$results = DB::table('orders')
->select(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m") as delivery_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
->whereBetween(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")'), [$data['start_year_month'],$data['end_year_month']])
->groupBy(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")'))
->get();
You can try this!
$results = DB::table('orders')
->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
->groupBy(function ($val) {
return Carbon::parse($val->start_time)->format('y'); });

Laravel get row with records above and below it

I have a Laravel 4.2 project where I get data from a SQL DB and I can display onto the page. I can select the single record just fine, but I want to also show the records around the one selected.
For example, I want to show the 5 records above and below the one selected. Im not sure how to do this in Laravel.
$gradschoolrange = MOGRadschool::where('Title', '=', $gradschool)->get();
In the above example $gradschool might be "Test College", it will return that with a value, but I want to show all the other related records around it with those values too. The results should look something like this:
ABC College
Another College
Blah College
Go To College
Test College
Yet Another College
Yo Yo College
College College
Something College
Eating College
As there's no ordering specified in your initial query, I'm assuming you want 5 next/previous records according to primary key (id? - if not, you would obviously need to change that) in the table?
Given that IDs may not be numerically sequential, we can't simply assume that the previous 5 rows will be the ID of the row with title = $gradschool minus 5, so wondered if this might work:
$initial = MOGRadschool::where('Title', $gradschool)->first(); // get the initial row with the title of $gradschool
$result = MOGRadschool::where('id', '<', $initial->id)->take(5)->orderBy('id', 'DESC') // new query getting the previous 5 rows, by ID
->union(MOGRadschool::where('id', '>', $initial->id)->take(5)) // union a second query getting the next 5 rows by ID
->get() // get the result as a collection
->add($initial) // add the initial row to the collection
->sort(); // sort the collection (by id) so that the initial row is in the middle
So the output is a collection containing the initial row in the middle, with up to 5 records either side. You also have the initial row to highlight the output, if you need that.
If you want it based on the IDs, which is what I understand from your issue, something like this should work:
$selectedGradSchool = MOGRadschool::where('Title', '=', $gradschool)->get()->first();
$aboveSelected = MOGRadschool::where('id', '<=', $selectedGradSchool->id)
->orderBy('id', 'desc')
->take('5')
->get();
$belowSelected = MOGRadschool::where('id', '>' $selectedgradSchool->id)
->take('5')
->get();
//Concatenate both results
$schoolRange = $aboveSelected->concat($belowSelected);
Now the collection should look similar to your desired result.

Laravel groupBy take n groups

Let's say I have a table users with thousands of records, each with their name.
My goal is to draw a pie chart showing the most common names. I want to take, for example, the 9 most common names, and put the rest into a 'others' group.
I can't figure out how to use groupBy() and take(), or whatever, to achieve this.
Any ideas?
You can try using groupBy and count raw
$groups = DB::table('users')
->select(DB::raw('count(*) as user_count, name'))
->groupBy('name')
->orderBy('user_count', 'desc') //lorder desc or asc
->limit(5) //number of groups
->get();
dd($groups); you will see the user_count and name
Data for your pie chart would be user_count/total_user

Query Builder summarize the field value depending on another field

I have some table
I need select an group iformation from these, but a have some conditions:
Group results by date (day). Ideally when day start on 09.00 and finsh 09.00 (24hr)
Then i need summarize values field sum where 'satus_id' = 10 into new variable example 'TotalIn' and where status_id = 12 into variable example TotalOut
Give results on view (but this no problem)
How to do it?
I write this, but i now this is wrong:
$statistic = DB::connection('mysql2')->table('payout_transactions')
->selectRaw('*, DATE(date) as day')
->where('status_id', 12)
->selectRaw('SUM(sum) AS TotalIn')
->groupBy('day')
->get();
What you could consider is:
DB::table('market')
->selectRaw('SUM(sum) as total, status_id, DATE("date") as day')
->whereIn('status_id', [10,12])
->groupBy([DB::raw(DATE('date')), 'status_id'])
->get()
That should give the sums for day, separately for both status_ids (10 or 12).

Resources