Laravel Eloquest join with max adn min value - laravel

Im trying to build a query that pulls the information from one table and also pulls the max and min value of that product in another table but cannot seem to get this to work.
This is what I have:
$rentals = Rentals::select('rentals.main_image','rentals.rental_name','rentals.slug','rentals.summary',DB::raw('max(prices.price) as price_high'),DB::raw('min(prices.price) as price_low'))
->leftjoin('prices', 'rentals.id', '=', 'prices.rental_id')
->where('destination',$destination_id)->paginate(6);
This returns 1 row ( there should be 88 ) and it gets me the highest and lowest price in the table regardless of rental_id. There are other factors that will filter into this like dates but for now I just need the rental info plus the highest and lowest price for that rental.

Related

DAX formula to get total number of sales in a Calculated Column at a lookup table

I have received answers to my last question. Thanks to all. Now I have another query. I have a lookup table, called Products and a transaction table, called Sales. The relationship between them is one to many. I want to make a Calculated Column at Product to get the total number of sales for each product. I tried to apply Calculate function as solution.
Product [total number of sales] =
Countrows ( Filter (Product, Calculate (Sum( Sales [SalesAmount])))).
I expected products in each row in Product table shall filter the sum of sales amount and generate a virtual table with all the entries related to a particular product. And finally, Countrows shall count the number of entries. But on the contrary, it resulted with same number in each row.
I am just a beginner in DAX. I tried to solve it depending on context transition concept. But my guess was wrong. Please help me out. Thank you in advance.
Use RELATEDTABLE:
If you just want the number of entries in the Sales table per product:
=
COUNTROWS(
RELATEDTABLE( Sales )
)
If you want the total sales per product:
=
SUMX(
RELATEDTABLE( Sales ),
Sales[SalesAmount]
)

TOPN DAX function not working. The formula is returning all the rows and not TOP 3

My goal is to create measure to get top 3 customer Names and there respective sales.
I am using the below measure to bring top 3 names along with there sales. The below measure is returning all the rows. I fail to understand why this is happening and why filtering is not happening for top 3 customers
topN = calculate(sum(Sale[Total Excluding Tax]),
TOPN(3,
values(Sale[Employee Name]),
calculate(sum(Sale[Total Excluding Tax]))
)
)
Sale[Employee Name] is calculated column and is coming from another table Employee by using Employee Name = RELATED(Employee[Employee])
The DAX is working properly and grabbing top 3 records. Order/sorting is important. You need to order your results.
Create a calculate column [Total Excluding Tax] to sum up the Total excluding tax. Then use that column in a measure; try something like:
Top Sales = TOPN ( 3, ALLSELECTED( 'Sale' ), [Total Excluding Tax]), desc)

How to filter by measure values in MDX while having dimension members in both axis

I'm developing an application that uses a tabular database to show some business data.
I need to provide some basic filtering over measures values (equal to, greater than, lesser than etc.) and I'm currently analyzing the proper way to generate the MDX.
Looking at some documentation (and other threads on this site), I found that the most efficient approach would be using the FILTER or HAVING functions to filter out undesired values.
Unfortunately all examples normally include measures on one axis and dimension member on the other, but I potentially have dimension members in both axis and can't find a proper solution to use such functions to filter by measure value.
What have I done so far?
To make it easier to explain, let's say that we want to get the yearly sales quantities by product class filtering quantity > 1.3 milions
Trying to use HAVING or FILTER Functions, the resulting MDX I came up with is
SELECT
NON EMPTY {[YearList].[Year].[Year].MEMBERS * [Measures].[Qty]}
HAVING [Measures].[Qty] > 1.3e6 ON COLUMNS,
NON EMPTY {[Classes].[cClass].[cClass].MEMBERS}
HAVING [Measures].[Qty] > 1.3e6 ON ROWS
FROM [Model]
or
SELECT
NON EMPTY FILTER({[YearList].[Year].[Year].MEMBERS * [Measures].[Qty]},
[Measures].[Qty] > 1.3e6) ON COLUMNS,
NON EMPTY FILTER({[Classes].[cClass].[cClass].MEMBERS} ,
[Measures].[Qty] > 1.3e6) ON ROWS
FROM [Model]
But this is of course leading to unexpected result for the final user because the filter is happening on the aggregation of the quantities by the dimension on that axis only, which is greater then 1.3M
The only way I found so far to achieve what I need is to define a custom member with an IIF statement
WITH
MEMBER [Measures].[FilteredQty] AS
IIF ( [Measures].[Qty] > 1.3e6, [Measures].[Qty], NULL)
SELECT
NON EMPTY {[YearList].[Year].[Year].MEMBERS * [Measures].[FilteredQty]} ON COLUMNS,
NON EMPTY {[Classes].[cClass].[cClass].MEMBERS} ON ROWS
FROM [Model]
The result is the one expected:
Is this the best approach or I should keep using FILTER and HAVING functions? Is there even a better approach I'm still missing?
Thanks
This is the best approach. You need to consider how MDX resolves result. In the example above it is a coincidence that your valid data in a continous region of first four columns of first row. Lets relax the filtering clause and make it >365000. Now take a look at last row of the result, the first two columns and the last column are eligible cells but the third and fourth column is not eligible. However your query will report it as null and the non empty function will not help. The reason is that non empty needs the entire row to be null
Now the question that why filter is not eliminating the cell? Filter will eliminate a row or column when the criteria is greater then the sum on the other axis. So if filter is on columns the filter value has to be greater than the sum of rows for that column. Take a look at the sample below as soon as you remove the comments the last column will be removed.
select
non empty
filter(
([Measures].[Internet Sales Amount]
,{[Date].[Calendar Year].&[2013],[Date].[Calendar Year].&[2014]}
,[Date].[Calendar Quarter of Year].[Calendar Quarter of Year]
),([Date].[Calendar Year].currentmember,[Date].[Calendar Quarter of Year].currentmember,[Product].[Subcategory].currentmember,[Measures].[Internet Sales Amount])>45694.70--+0.05
)
on columns
,
non empty
[Product].[Subcategory].members
on rows
from
[Adventure Works]
Edit another sample added.
with
member [Measures].[Internet Sales AmountTest]
as
iif(([Date].[Calendar Year].currentmember,[Date].[Calendar Quarter of Year].currentmember,[Product].[Subcategory].currentmember,[Measures].[Internet Sales Amount])>9000,
([Date].[Calendar Year].currentmember,[Date].[Calendar Quarter of Year].currentmember,[Product].[Subcategory].currentmember,[Measures].[Internet Sales Amount]),
null
)
select
non empty
({[Measures].[Internet Sales Amount],[Measures].[Internet Sales AmountTest]}
,{[Date].[Calendar Year].&[2013]}
,[Date].[Calendar Quarter of Year].[Calendar Quarter of Year]
)
on columns
,
non empty
[Product].[Subcategory].[Subcategory]
on rows
from
[Adventure Works]

How to get the difference between the values selected by slicer?

I am new to Power BI and currently I am working with table visulaizations and slicers.
My data is as follows
Student table:
Date table:
Exam table:
The relationships within the table are as follows:
I want an output like the image shown below, I would like to create 2 table visuals that can be filtered on Student Name, Classroom and also have slicer on 2 dates. I need to compute minimum score. The user must be able to select 2 dates at a time on the slicer, the first date selected on the slicer should be attached to my 'Min Score at date1' and second date selected on the slicer should be attached to my 'Min Score at date2', and the third column 'Difference in Score' must be able to calculate the difference between the Min Score at date1 and Min Score at date2.
Similarly I also want to calculate the average minimum score too
Please let me know how to proceed or what alternative formula or query or method should I apply to get the desired result.Thanks!
Before I start, let me mention that this example was done in SSAS so it may need some tweaking in PowerBi but the logic is identical nonetheless.
First create a clone date table and call it something else e.g. 'Compare Date'. Next, create an inactive, one to many relationship between the 'Compare Date' and your 'Fact' table, see the image below, in this case I am joining on [Year Month], you will need to adjust to fit your needs:
If you are unsure how to do this, just right click on the new table and select the create relationship option, ensure that the relationship is like the image below:
Once this has been done, right click on the 'relationship' and mark it as inactive.
Now that you have the new date table and the relationships set up, I want you to create a few DAX measures:
Min Date 1 = Min('Student Table'[Score])
Min Date 2 = CALCULATE(Min('Student Table'[Score]), ALL('Dates'), USERELATIONSHIP('Compare Date'[Date], 'Fact'[Date]))
Avg Date 1 = AVERAGE('Student Table'[Score])
Avg Date 2 = CALCULATE(AVERAGE('Student Table'[Score]), ALL('Dates'), USERELATIONSHIP('Compare Date'[Date], 'Fact'[Date]))
Delta Min = [Min Date 2] - [Min Date 1]
Delta Avg = [Avg Date 2] - [Avg Date 1]
These measures will calculate exactly what you need and can be filtered independently via two date slicers tied to each date table. The rest is just busy work.
I hope this helps.

how to I define measurement filter from other table in tabular

I am trying to make measure that gets sum of amt column where versiontype column = ative how do I write dax formula for that measure?
So let's say your fact table is called Sales. It has a Sales Amount called Amt. The table is linked to a Version table with a VersionType field that includes a value of "Active".
You could create a new measure for Active Sales as follows:
ActiveSales :=
CALCULATE (
SUM ( Sales[Amt] ),
'Version'[VersionType] = "Active"
)

Resources