Extract more rows from a left join with Laravel - laravel

I have to extract the rows where the created_at is inside the week. Unfortunately, only one line is extracted from me and no more lines as I expected. Why?
Query:
$scadenze = DB::table('processi')
->leftJoin('scadenze', 'processi.id', '=', 'scadenze.processo_id')
->where('responsabile',$utente->id)
->whereNotIn('scadenze.stato', [4,5])
->whereBetween('scadenze.termine_stimato',[\Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
->avg('tempistica');
This query extract just one row, but in reality many more lines should be extracted.

Because ->avg('tempistica'); return average value from all your rows in this query, i.e. return just one value.

Solution:
I was wrong to use the avg with sum function. The rows were extracted correctly but instead of being added (by timing) an average was made. Thank you all for your help.

Related

PowerPivot DAX Max of two values

I have two columns and I need to extract the maximum value of those two for every row in my table. I have looked at the Max, Maxx and Maxa, but they all have input for just one column.
How would I write following expression in a Calculated column:
=max(
Table1[Column1],
Table1[Column2]
)
Actually, you should write the formula exactly as you described:
=max(
Table1[Column1],
Table1[Column2]
)
MAX function in dax exists in 2 versions: one takes a single column, the other takes 2 singular expressions.
Instead of MAX, you can just use a simple IF to achieve what you want:
= IF(Table1[Column1] >= Table1[Column2], Table1[Column1], Table1[Column2])

laravel ->count() vs ->get()->count()

Why are the two statement below behaving differentlY? The first returns 3 the second returns 1 for $progress. I thought that the first aggregates on the DB and the second on the server. So they should still return the same value.
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->get()->count();
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->count();
->get()->count() will load Eloquent model objects into memory and then will count those.
->count() will use DB aggregate function, so it will definitely be more efficient:
select count(*) as aggregate ...
It's quite late answer but I had faced the same issue. These two examples are returning two different counts because of groupBy you have used.
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->get()->count();
This takes the rows first, then count the row numbers and returns the count.
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->count();
Whereas this counts the rows by its group in the DB and returns the first group's row record count only from the list.
the solution I used instead of get()->count() for my case is like
$progress = $this->user->userActivities()
->distinct('date')
->count('date');
Use ->get()->count() is wrong. I used ->get()->count() in my web app and when my database records have more than 80000 records I get error 500 in my app.
The first counts the number of returned records, the second counts the records and returns the number. If you are using a paging of 10, for example, then the first will yield 10 and the second the actual number if the number of mathcing elements is greater than 10.
$count = Model::all()->count();
return view('home',compact('count'));
this will function for laravel 6;
Both of them return the same result. But as said for preventing to crash or decrease the speed of response it's better to use count() instead of get()->count()

Propel, selecting just one column

I am trying to run a query in propel that runs an aggregate function (SUM).
My Code
$itemQuery = SomeEntity::Create();
$itemQuery->withColumn('SUM(SomeColumn)', someColumn)
->groupBy(SomeForeignKey);
Problem
It should theoretically return the sum of every group of items but the problem is propel tries to fetch all columns, and also appends a bunch of other columns to the group by clause. This results in an unexpected categorisation and therefore the sum is incorrect.
Is there anyway to make propel fetch just the column I am running the aggregation function on so that the group by statement works as well?
You need to add a select statement for the column and the foreign key:
$itemQuery = SomeEntity::Create();
$itemQuery->select(array(SomeColumn, SomeForeignKey));
$itemQuery->withColumn('SUM(SomeColumn)', someColumn);
$itemQuery->groupBy(SomeForeignKey);

Laravel Eloquent how to get the second or third record?

I have an Order and a Product models.
"Order" HasMany Product (and Product belongsTo Order)...
Let's say I want to display the 3 products of my order, how to do that ?
I know the first could be retrieved like $order->products->first()... but how to retrieve the second and third product?
I tried $order->products->find(1) but "1" represents the id of the product... which I don't want to know...
$order->products()->skip(1)->first();//Second row
$order->products()->skip(2)->first();//Third row
....
Is more performant than loading all products and getting only first, second, ecc..
Instead if you want both second and third, you can get only them in a single query without load other rows, with similar approach:
$order->products()->skip(1)->take(2)->get(); //Skip first, take second and third
I finally found the solution, this is the correct syntax:
$order->products->get(0)->name; will return the first record
$order->products->get(1)->name; will return the second record
$order->products->get(2)->name; will return the third record
And so on...
$order->products()->skip(1)->take(1)->first(); //Second row
$order->products()->skip(2)->take(1)->first(); //Third row
$order->products()->orderBy('salary','desc')->skip(1)->take(1)->first(); //Second highest salary row
$order->products()->orderBy('salary','desc')->skip(2)->take(1)->first(); //Third highest salary row
Say you want a second product from Eloquent Collection
if you are sure that the array keys are same as array indexes, do that
$order->products->get(1)->name;
if you need the second item and you are not sure about the array keys, do this
$order->products->slice(1, 1)->first()->name;
You can simply try this :
$order->products->take(3)->get();

SOQL - single row per each group

I have the following SOQL query to display List of ABCs in my Page block table.
Public List<ABC__c> getABC(){
List<ABC__c> ListABC = [Select WB1__c, WB2__c, WB3__c, Number, tentative__c, Actual__c, PrepTime__c, Forecast__c from ABC__c ORDER BY WB3__c];
return ListABC;
}
As you can see in the above image, WB3 has number of records for A, B and C. But I want to display only 1 record for each WB3 group based on Actual__c. Only latest Actual__c must be displayed for each WB3 Group.
i.e., Ideally I want to display only 3 rows(one each for A,B,C) in this example.
For this, I have used GROUPBY and displayed the result using AggregateResults. Here is the result.
I got the Latest Actual Date for each WB3 as shown above. But the Tentative date is not corresponding to it. The Tentative Date is also the MAX in the list.
Here is the code I used
public List<SiteMonitoringOverview> getSPM(){
AggregateResult[] AgR = [Select WB_3__c, MAX(Tentaive_Date__c) dtTentativeDate , MAX(Actual_Date__c) LatestCDate FROM Site_progress_Monitoring__c GROUP BY WBS_3__c];
if(AgR.size()>0){
for(AggregateResult SalesList : AgR){
CustSumList.add(new SiteMonitoringOverview(String.ValueOf(SalesList.ge​t('WB_3__c')), String.valueOf(SalesList.get('dtTentativeDate')), String.valueOF(SalesList.get('LatestCDate')) ));
}
}
return CustSumList;
}
I am forced to use MAX() for tentative date. I want the corresponding Tentative date of the MAX Actual Date. Not the Max Tentative Date.
For group A, the Tentative Date of Max Actual Date is 12/09/2012. But it is displaying the MAX tentative date: 27/02/2013. It should display 12/09/2012. This is because I am using MAX(Tentative_Date__c) in my code. Every column in the SOQL query must be either GROUPED or AGGREGATED. That's weird.
How do I get the required 3 rows in this example?
Any suggestions? Any different approach (looping within in groups)? how?
Just ran into this issue myself. The solution I came up with only works if you want the oldest or newest record from each grouping. Unfortunately it probably won't work in your case. I'll still leave this here incase it does happen to help someone searching for a solution to this issue.
AggregateResult[] groupedResults = [Select Max(Id), WBS_3__c FROM Site_progress_Monitoring__c GROUP BY WBS_3__c];
Calling MAX or MIN on the Id will let you get 1 record per group condition. You can then query other information. I my case I just need 1 record from each group and didn't really care which one it was.

Resources