Query Builder summarize the field value depending on another field - laravel

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).

Related

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'); });

how to get result count group by day in laravel

Hello Everyone can you please help me to resolve this
I want to get the user count day-wise, for example, I want to know how many users registers in last week
like date of
22-07-19
user count 20
23-07-19
user count 30
24-07-19
user count 10
25-07-19
user count 15
I want this result for last 7 day from today
basically, I want to show this in my chart please check the image here
By selecting DATE(created_at) and grouping by that, we can get the count of users that have registered each day. We can then add a simple where clause, using Carbon to help us get the lower bounds.
Example (where x = date and y = count):
User::selectRaw('DATE(created_at) as x, COUNT(*) as y')
->groupBy('x')
->where('created_at', '>', Carbon::now()->subWeek())
->get();

Power Query (M language) 50 day moving Average

I have a list of products and would like to get a 50 day simple moving average of its volume using Power Query (M).
The table is sorted by product name and date. I add a custom column and applied the code below.
if [date] >= #date(2018,1,29)
then List.Average(List.Range(Source[Volume],[Volume]-1,-50))
else ""
Since it is already sorted by date and name, an if statement was applied with a date as criteria/filter. However, an error occurs that says
'Volume' column not found in the table.
I expect to have an added column in the power query with volume 50 day moving average per product. the calculation to be done if date is greater than or equal Jan 29, 2018.
We don't know what your columns are, but assuming you have [product], [date] and [volume] in Source, this would average the last 50 days of [volume] for the identical [product] based on each [date], and place in a new column
AvgAmountAdded = Table.AddColumn(Source, "AverageAmount", (i) => List.Average(Table.SelectRows(Source, each ([product] = i[product] and [date]<=i[date] and [date]>=Date.AddDays(i[date],-50)))[volume]), type number)
Finally! found a solution.
First, apply Index by product see this post for further details
Then index again without criteria (index all rows)
Then, apply below code
= Table.AddColumn(#"Previous Step", "Volume SMA(50)", each if [Index_byProduct] >= 50 then List.Average(List.Range(#"Previous Step"[Volume], ([Index_All]-50),50)) else 0),
For large dataset, Table.Buffer function is recommended after index-expand step to improve PQ calculation speed

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.

Combining all dates, and data, within a month!

I am trying to combine all days of each month into a date.
My query as off now:
SELECT
inventory_items.acquired_at AS Date_Acquired,
products.name AS products_name,
SUM(inventory_items.primary_quantity) AS inventory_items_primary_quantity
FROM
inventory_items inventory_items INNER JOIN customers customers ON inventory_items.source_id = customers.id
INNER JOIN products products ON inventory_items.product_id = products.id
GROUP BY
MONTH(Date_Acquired),
products_name
ORDER BY
MONTH(Date_Acquired)
I have a general idea of what to do, but not really sure how to implement it.
As I understand you and your Date_Acquired is an instance of sql Date type
you can gat day of months as pasting below code inside a textfield
(new SimpleDateFormat("d")).format(new java.util.Date())
which suppose to give you numbers like 1,2,3,...18,19...
Extra:
(new SimpleDateFormat("M")).format(new java.util.Date()) for month
(new SimpleDateFormat("yyyy")).format(new java.util.Date()) for year
(new SimpleDateFormat("d")).format(new java.util.Date())+" - "
+(new SimpleDateFormat("M")).format(new java.util.Date()) for getting a value like 28 - 01
What database? A typical SQL database result can only contain one data value per field. So you will not be able to retrieve all the products.name values in one result grouped by the month. If you retrieve all the results under a specified month you can aggregate them later on.

Resources