Selecting items that are not in another table or are not within a given date range - linq

I'm working on a program that keeps a list of physical advertisement spots and their reservations (a date range). The program needs to be able to find "open spots" for ads within an ad category.
I have three tables: AdTypes, AdPlaces and Reservations. Currently, I'm implementing a query that searches for reservations where the dates don't collide with the date range the user selected, and returns the AdType items as a list. This method works if every AdType has had an reservation at some point, but it doesn't list AdTypes that are not found in the Reservations table.
The filtering is done in PreProcessQuery of an AdTypes query, as such:
query = query.Where(r => r.Reservations.Any(res => (res.Begindate > Begindate && Enddate < res.Enddate) || (res.Enddate < Begindate && Enddate > res.Begindate)));
How can I "extend" the query so that all those AdTypes that have no reservations would be listed alongside "expired" AdType reservations?

Maybe I'm mssing something, or not quite understanding what you want, but how can you expect see AdTypes that don't exist?
Is it that you want to see the AdTypes that don't have any reservations during the period you're testing for?
If so, I imagine you'd have to use the adType entity as the basis of your screen, not the Reservation entity (with a query based on AdType, not Reservation). That way you can produce a list of AdTypes that don't have any overlapping reservations.
Does that make any sense?

Related

DAX/POWERBI : count tickets attached to an item and all its child items

I am new to DAX and PowerBI and have a problem to write DAX formulas for my case:
I have two tables: Assets and Tickets. Each have an Id, and the Assets have a ParentAssetId (can be 0 or None).
In a DAX expression: I would like to count (and list) all the tickets attached to an Asset and its children.
I tried this way but without success:
nbChildTickets =
VAR mykey =
SELECTEDVALUE ( Assets[AssetKey] )
VAR mypar =
SELECTEDVALUE ( Assets[ParentId] )
RETURN
CALCULATE(
COUNTX(Tickets, Tickets[TicketKey]),
FILTER(Tickets, RELATED(Assets[ParentId]) = mykey)
)
The Tables and the Canvas
It is the asset table which contains both the AssetKey and the ParentId colums.
Have any idea or tuto to do this ?
Thanks
A question, are these tables already related? In case they are, it seems that you wouldn't need a measure like that to get the count of # of tickets by asset and its parent. I would do it in the next two ways. Supposing you need it in a table:
Option 1.
Create a simple count measure to get the number of tickets in Tickets table, it could be something like Number of Tickets = COUNTROWS('Tickets')
Drag a table to the canvas.
Add to the table Assets and its children columns, finally add your new measure to the table
Option 2. In case each ticket has an ID.
Drag a table to the canvas.
Add to the table Assets and its children columns. Also add your tickets Id.
At Fields section (where you drag and drop your columns, right click and select the Count option.
Done
Remember, it is important that your both tables are already related to work. Otherwise Power BI will not know how to calculate and displays this combination of data for you.
First create two relationships between Assets and Ticket table. One relationship will be active (one to many) on column AssetKey Column.
Second relationship will be Inactive. Asset[AssetKey] = Ticket[ParentID]
Now use the below Measures -
Number Of Tickets = COUNT(Tickets[TicketKey])
Number of Child = CALCULATE(COUNT(Tickets[AssetKey]),USERELATIONSHIP(Asset[AssetKey],Tickets[ParentId]))
Relationship diagram is in below image :
Output is mentioned below:
The blank row can be eliminated from visual filters :

Power Pivot and Closing Price

I am trying to use power pivot to analyze a stock portfolio at any point in time.
The data model is:
transactions table with buy and sell transactions
historical_prices table with the closing price of each stock
security_lookup table with the symbol and other information about the stock (whether it’s a mutual fund, industry, large cap, etc.).
One to many relationships link the symbol column in security_lookup to the transactions and historical_prices tables.
I am able to get the cost basis to work correctly by doing sumx(transactions, quantity*price). However, I’m not able to get the current value of my holdings. I have a measure called “Current Price” which finds the most recent closing price by
Current Price :=
CALCULATE (
LASTNONBLANK ( Historical_prices[close], min[close] ),
FILTER (
Historical_Prices,
Historical_prices[date] = LASTDATE ( historical_prices[date] )
)
)
However, when I try to find the current value of a security by using
Current Value = sumx(transactions,transactions[quantity]*[Current Price])
the total is not accurate. I'd appreciate suggestions on a way to find the current value of a position. Preferably using sumx or an iterator function so that the subtotals are accurate.
The problem with your Current Value measure is that you are evaluating [Current Price] within the row context of the transactions table (since SUMX is an iterator), so it's only seeing the date associated with that row instead of the last date. Or more precisely, that row's date is the last date in the measure's filter context.
The simplest solution is probably to calculate the Current Price outside of the iterator using a variable and then pass that constant in so you don't have to worry about row and filter contexts.
Current Value =
VAR CurrentPrice = [Current Price]
RETURN SUMX(transactions, transactions[quantity] * CurrentPrice)

PowerBi DAX equivalent for SUMIFS with current row value as filter

In Excel I could, if I was in a table called 'Sales' that had four columns
Sales
Month, CustomerId, ProductId, TotalQuantity
Jan,1, CAR,
Feb,1, CAR,
I could add a formula:
=SUMIFS(Sales[Quantity],Sales[CustomerId],[#[CustomerId]])
That would go to the Sales table and sum the CustomerID column filtered by the CustomerID of the current row where the formula has been entered.
I am attempted to replicate this in a PowerBI Calculated Row but I can't get the # working for a row reference. It comes across like
TotalQuantity = CALCULATE(SUM(Sales[Quantity]),Sales[CustomerId] = Sales[CustomerId]))
Any idea how to get the equivalent # working?
I think the key function you are missing is EARLIER. That is not surprising because it has a misleading name - it really means "Current Row". You also need a FILTER function in the Filter parameter of CALCULATE, to reset the filter context to the entire table.
So your New Column function might look like this:
TotalQuantity = CALCULATE(SUM(Sales[Quantity]), FILTER(Sales, Sales[CustomerId] = EARLIER (Sales[CustomerId])))
Here's a neat example, from the most accessible source site for DAX formulas:
http://www.powerpivotpro.com/2013/07/writing-a-subtotal-calc-column-aka-the-simplest-use-of-the-earlier-function/
And FWIW here is the official doco on EARLIER:
https://msdn.microsoft.com/en-us/library/ee634551.aspx

Get first record of each entity order by a column

I have a query in linq that fetch students assessments data something like
new {x.StudentId, x.StudentAssessmentId, x.AssessmentName, x.SubmittedDate}
then I perform some operations on this list to get only last added student assessment per student, I get last studentassessment by finding the max id of studentassessment,
so I finally get last studentassessments data of all the students.
Is there a way to do this directly in the initial list?
I thought about the way to group the results by student Id and select max of studentassessmentid, like
group x.StudentAssessmentId by x.StudentId
select new {x.Key, x.Max()}
in this way I will get student with there last studentassessmentid which is what I want but this will only give me studentassessment ids while I want other data also like AssessmentName, SubmittedDate etc.
Try something like this:
group x.StudentAssessmentId
by new {
x.StudentId,
x.AssessmentName,
x.SubmittedDate }
into g
select new
{
g.Key.StudentId,
g.Key.AssessmentName,
g.Key.SubmittedDate,
g.Max(),
}

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