For simplicity, assume a database with the following columns:
Table: Tickets
Columns:
Gender, Quantity, Date
where Gender can be M or F. A row is inserted for every purchase. Ultimately I want a stacked bar chart that shows the quantity purchased by males and females each month.
I can't seem to find a way to do this that doesn't require 2 queries, one that sums for M per month and one for F per month. The problem is that the query sets may not have the same number of objects and may not be in the same order by date.
I've tried:
set = Model.objects.filter(date__month = month).values('gender').aggregate(Sum('quantity'))
This sorts by date but doesn't separate M from F.
Adding M or F as a filter yields the correct quantity for one of the groups.
Using two queries(one for each of M, F) yields the correct quantities and date ranges but doesn't necessarily yield an identical number of sets. (eg. if in some months there are no purchases by M).
Thanks in advance for guidance.
You can use the following Statement :
Model.objects.filter(date__month = month).values('gender'). \
annotate(total=Sum('quantity'))
in order to sum the quantity per gender per month
Related
I am trying to use a measure to find the total impact of a price change.
Currently, I have a table with the date, region, product quantity, and revenue.
I have measures that return YTD and PY YTD for both revenue and product quantity.
AvePriceYTD = Rev YTD/ Q YTD and AvePricePYYTD = RevPYYTD/Q_PYYTD
My final measure is PE = (AvePriceYTD-AvePricePYYTD)*Q_PY
When totaling the AvePriceYTD-AvePricePYYTD is correct but when multiplying Q_PY it gives a different result to the sum of the individual PE for each region.
I know that this involves the HasOneFilter to choose the total but not sure how to evaluate each region individually and then total. It is not possible to evaluate each row as this is monthly data and there are multiple rows per region.
https://community.powerbi.com/t5/Quick-Measures-Gallery/Measure-Totals-The-Final-Word/m-p/547907
This link explains the answer, I initially didn't realize that the _table and _value were actually mean to be typed and not replaced with your own text.
Just wanted to confirm my understanding (or lack thereof) around these two formulas - in an orders table where each row is an order:
TOPN(10,ALL(Orders),[Total Sales]) - looks at the individual Sales amount for each row and returns the whole table with just the top 10 records sorted by the Sales field; using the measure Total Sales(defined as Sum of Sales) in this context doesn't really have an effect as the aggregation is at a single row level which just keeps it the same.
TOPN(10,ALL(Orders[Customer Name]),[Total Sales]) - this actually groups by the customer name, calculates the total sales, and returns the top 10 customer names based on that metric; it's more or less equivalent to this SQL:
select customer_name, sum(sales) as Total_Sales from orders
group by customer_name
order by Total_Sales desc
limit 10
I'm trying to calculate a monthly average number of cases for each investigator. It might be over a quarter, year, or multiple years so it needs to respond to the visual or table context I drop it into. The base table has Case (individual case#), Investigator (person name), Date assigned (not shown), and from that date,month and year columns extracted and a YearMonth categorical column.
I create a caseCount measure as
caseCount = COUNT('Table'[Case])
I've tried several different ways to calculate the average over all months (in this case 4). Because Mary has cases in each month, her average is correct (1.75) but Sam's uses a denominator = 3, thus doesn't calculate correctly. (returns 1.3 instead of 1). How can I force the calculation to use the full number of months.
Additional notes:
There may be cases in the table that fall outside the date range I want so I've tried using a
Avg = CALCULATE(AVERAGE(caseCount), Table[Date] > #10/31/2019#)
I've also tried several variations using CALCULATE(DIVIDE(), [Date] > 10/31/2019. Everything seems to exclude those months when an investigator had no investigations assigned. I also tried connecting to a Date table and using the Distinct YearMonth value created there.
This is because the evaluation context.
I would define the measure as follow:
VAR _casecount = //count number of cases in the selected period, applied on the fact table
VAR _months = COUNTROWS(CALCULATETABLE(VALUES('Calendar'[Month]), ALLSELECTED('Calendar'))) //count number of months in the selected period
RETURN
_casecount/months
Update
I did not consider the scenario of multi-year periods involving May-2019 and May-2020. Then, let's reframe the solution using DATEDIFF:
VAR _casecount = //count number of cases in the selected period, applied on the fact table
VAR _firstCalendarDate = CALCULATE(MIN('Calendar'[Date], ALLSELECTED('Calendar'))
VAR _lastCalendarDate = CALCULATE(MAX('Calendar'[Date], ALLSELECTED('Calendar'))
VAR _months = DATEDIFF(_firstCalendarDate, _lastCalendarDate, MONTH)
RETURN
_casecount/months
I couldn't find an answer for my issue elsewhere, so trying my luck here.
I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:
For ID 123 I have to flag it that sale for products A,B,C where within specified period.
For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.
I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day
For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.
After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.
If someone can give me direction for that much appreciated
Thank you in advance
You could use a DateTable like this one:
I used the following DAX-expressions for the calculated columns:
nrDays = 7
isWorkDay = WEEKDAY('DateTable'[Date],2) < 6
rankWorkingDays = RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
DateTable[Date] , , ASC )
LastWorkDay = LOOKUPVALUE ( DateTable[Date],
DateTable[isWorkDay], TRUE (),
DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date
I have a table with country and population for 2017, and I have another table with country and population growth rate%. And I have one table with years like (2018 to 2028). I am trying to find calculated population for 10 years on the basis of these data as we are calculating compound interest.
Because you are working with growth rates, it is very unlikely that you will want to do this calculation as a measure. Rates don't aggregate well.
So, the first thing you're going to want to do is get your data into one table. I would do this in query editor.
You'll need a Cartesian join between your list of countries and a list of years. The PowerBI method for this is a little non-intuitive. You add a custom column, and in the formula you just type in the name of the table.
The result is that every single row in the countries table will be matched with every single row from the years table. If you have 5 rows in one and 10 rows in the other, the resulting table is 50 rows.
Then Merge in your table with the growth rates. Now you have a table that has the name of the country, the 2017 starting population, the growth rate. This set of rows will be repeated for every year from 2018 - 2028.
There is a specific formula for cumulative (compounded) growth.
Pricipal * ( 1 + RatePerPeriod / NumberOfCompoundsPerPeriod) ^ (NumberOfPeriods * NumberOfCompoundsPerPeriod)
You're doing this annually, so it simplifies a bit
Pricipal * ( 1 + Rate) ^ (NumberOfYears)
And the M will look like this:
[2017 Population] * Number.Power((1 + [Growth]),([Year] - 2016))
Good Luck! Hope it helps.