First we get the crude rate which is cancer count/population count * 100,000, since cancer count might relate to the population of male/female ration, so need to turn the crude rate to standardized rate, so later we can compare rate among different populations, here the assumption of standard population of ratio of Female:Male = 51:49.
So the Gender Standardized Rate is:
Female crude rate * female percentage + Male crude rate * male percentage =
671.7 * 0.51 + 716.7 * 0.49 = 693.7
So for total standardized rate it will be 693.7, the rest standardized rate will be same as crude rate.
The question is how to implement it? How should I define it in Calculation like if currentmember.level = total then ... else [crude rate]
It seems that you want to ignore Undifferentiated, and calculate Satnsarized. You could try to use expression like below to see whether it will work or not
with member[Measures].[SalesCalc2] AS
(
IIF([Product].[Category].CurrentMember=[Product].[Category].&[3],"0",[Measures].[Internet Sales Count])
)
member[Measures].[SalesCalc3] AS
[Measures].[SalesCalc2] *[Measures].[Internet Sales Count]
select [Product].[Category].[Category] on rows, {[Measures].[Internet Sales Count],[Measures].[SalesCalc2] ,[Measures].[SalesCalc3] } on columns from
[Analysis Services Tutorial]
You could refer to this post for details
Zoe
The solution is to use SCOPE in calculation.
The purpose of using SCOPE is to do the calculation first, which is
Female crude rate * female percentage and Male crude rate * male percentage
then add them together, so the formula is
671.7 * 0.51 + 716.7 * 0.49 = 693.7
Please refer to the following link for steps to implement it:
https://blog.crossjoin.co.uk/2013/05/29/aggregating-the-result-of-an-mdx-calculation-using-scoped-assignments/
Related
The question is:For the previous Track, compute the weighted average (instead of the average) average yield by nation (yield is defined as dividend divided by price, and is reported as a percentage). The weighted average includes the quantity of shares as a weight.
But I have no clue on how to find a weighted average.
I already have some code that was used to compute the average of the yield in percent. But I'm having trouble computing the weighted average. I talked to some classmates and they said they're trying to use the formula: sum(x*w)/sum(w) where w is weight.
But I'm having trouble implementing this into my code
SELECT Nations.nationName,
AVG(dividend/price) AS Yield
FROM Shares, Nations
WHERE Shares.nationID=Nations.ID
GROUP BY Nations.nationName;
In the end the weighted average should be computer but I just don't know how to implement that into the code. The material we're supposed to base this problem off of is no help.
I followed you correctly, you should consider:
SELECT
n.nationName,
SUM(s.quantity * s.dividend / s.price)/IIF(SUM(s.quantity) = 0, NULL, SUM(s.quantity)) AS weighted_yield
FROM Shares s
INNER JOIN Nations n ON s.nationID = n.ID
GROUP BY n.nationName;
Notes:
always prefer explicit JOINs over old-school implicit JOINs
also, using table aliases are a best practice, since they make the query shorter and easier to follow
I have the following data:
DATE COUNTRY ITEM Value
2005-01-01 UK op_rate 30%
2005-01-01 UK proc 1000
2005-01-01 UK export 750
2005-01-01 ITA op_rate 45%
2005-01-01 ITA proc 500
2005-01-01 ITA export 350
Basically, data in normal format, which includes both ratios (the op_rate) and other items such as exported volumes and processed volumes ("proc").
I need to aggregate by SUM for "proc" and "export", but not for the "op_rate", for which I need a weighted average by "proc".
In this case the aggregated op_rate would be:
0.45*500 + 0.30*1000 = 0.35 // instead of a .75 SUM or 0.375 AVERAGE
All example I find for weighted average are across measures, but none covers using other dimensions.
Any help most welcome!
I understand that you are reluctant to change your model. The problem you have here is that you are trying to consume a highly normalised table and use it for analysis using an OLAP tool. OLAP tools prefer Fact/Dim star schemas and Tabular/PowerBI is no different. I suspect that this is going to continue to problems with future requirements too. Taking the hit on changing the structure now is the best time to do it as it will get more difficult the longer you leave it.
This isn't to say that you can't do what you want using the tools, but the resulting dax will be less efficient and the storage required will be sub-optimal.
So with that caveat/lecture given (!) here is how you can do it.
op_rate_agg =
VAR pivoted =
ADDCOLUMNS (
SUMMARIZE ( 'Query1', Query1[COUNTRY], Query1[DATE] ),
"op_rate", CALCULATE ( AVERAGE ( Query1[Value] ), Query1[ITEM] = "op_rate" ),
"proc", CALCULATE ( SUM ( Query1[Value] ), Query1[ITEM] = "proc" )
)
RETURN
DIVIDE ( SUMX ( pivoted, [op_rate] * [proc] ), SUMX ( pivoted, [proc] ) )
It is really inefficient as it is having to build your pivoted set every execution and you will see that the query plan is having to do a lot more work than it would if you persisted this as a proper Fact table. If your model is large you will likely have performance issues with this measure and any that references it.
#RADO is correct. You should definitely pivot your ITEM column to get this.
Then a weighted average on op_rate can be written simply as
= DIVIDE(
SUMX(Table3, Table3[op_rate] * Table3[proc]),
SUMX(Table3, Table3[proc]))
I'm trying to upgrade an application so that I can sell to multiple countries. I store all of my prices in the database in GBP excluding tax up to 4dp and I need to calculate the prices in the country's currency including tax.
Do I multiply the price by the exchange rate against the price excluding tax (option 1) or do I calculate the amount including tax and then multiple by the exchange rate (option 2)? I have also added an option 3 after looking at how OpenCart calculates it which is similar to option 2 but only ever rounds when displaying it. Here are the formula's for all 3 options:
Option 1:
Round((Price * Exchange Rate) / 100 * (100 + Tax Rate))
Option 2:
Round(Round(Price / 100 * (100 + Tax Rate)) * Exchange Rate)
Option 3:
Round((Price / 100 * (100 + Tax Rate)) * Exchange Rate)
For example say I have a product with a price of 89.99. If I wanted to display that in a currency with an exchange rate of 1.5 and a tax rate of 20%. Would I say:
Option 1:
Round((89.99 * 1.5) / 100 * (100 + 20)) = 161.98
Option 2:
Round(Round(89.99 / 100 * (100 + 20)) * 1.5) = 161.99
Option 3:
Round((89.99 / 100 * (100 + 20)) * 1.5) = 161.98
I've found that OpenCart always multiplies the unrounded figures by the exchange rate at the end. For example their formula for calculating the line total is:
Round((Price / 100 * (100 + Tax Rate)) * Quantity * Exchange Rate)
So if I was to order 3 of my product's it would give:
Round((89.99 / 100 * (100 + 20)) * 3 * 1.5) = 485.95
The problem I find doing it OpenCart's way is the user will see an item price (including tax) of 161.98 and a line total of 485.95. However if I say 161.98 * 3 I get 485.94, so it doesn't sum up correctly.
It's important I get this right as you can see I'll end up with penny issues. I'd appreciate it if someone could let me know which way is correct or suggest an alternative if none are right. Thanks
Since all variables are rounded except Exchange Rate, which I would expect to usually look something like this 1.3462, we can write a test like this:
// I'm guessing you need it in PHP
$price = 89.99;
$quantity = 1;
$tax = 20;
$tax = $tax/100.0 + 1;
// $tax = 1.2
$exchangeRate = 1.5;
$totalPrice = $price*$quantity*$tax; // Test #1
$totalPriceRounded = round($price*$quantity*$tax,2); // Test #2
echo $totalPrice.'<br/>'.$totalPriceRounded;
Which would have this output:
107.988 // Test #1 <--- This is amount that needs to be paid to you and Great Britain
107.99 // Test #2 <--- rounded
Now, it's obvious there is a difference in amount, so which to choose? Since you are charging an item from Great Britain, you expect to get paid the full amount you are asking for, in GBP, so lets rely on that factor. In the end, if I understood correctly, the tax the customer has to pay is tax to Great Britain.
Lets check the final prices in foreign currency:
$totalPrice = round($totalPrice * $exchangeRate,2);
$totalPriceRounded = round($totalPriceRounded * $exchangeRate,2);
echo $totalPrice.'<br/>'.$totalPriceRounded;
Which would have this output:
// Amount in foreign currency
161.98 // Test #1
161.99 // Test #2
With all that said, lets check which one of these would return you a value closest to 107.988 GBP when calculated back to GBP from foreign currency.
// To calculate the totalPrice back to price*tax*quantity in GBP
$totalPrice /= $exchangeRate;
$totalPriceRounded /= $exchangeRate;
echo $totalPrice.'<br/>'.$totalPriceRounded;
Output of which is:
// totalPrice in GBP currency
107.98666666667 // Test #1
107.99333333333 // Test #2
And when we divide by tax:
$totalPrice /= $tax;
$totalPriceRounded /= $tax;
echo $totalPrice.'<br/>'.$totalPriceRounded;
Output is:
// the amount you get in GBP currency
89.988888888889 // End result of Test #1
89.994444444444 // End result of Test #2
So as you can see, in this case, by using the bare amount of round($price*$quantity*$tax*$exchangeRate, 2) you are getting less, but by using round(round($price*$quantity*$tax,2)*$exchangeRate, 2) you get a little more which again, rounded both give the same value. In some other scenario the difference will likely be different from what we got here and might be the other way around.
CONCLUSION
If you have a fixed number of products each with fixed prices then you will be either loosing money (an insignificant amount) or earning more than you should (also an insignificant amount) over time. The outcome depends on the popularity and price of each product (i.e. will the round function round up or down), and on the way of calculation you chose. You could, depending on product popularity, manually adjust the prices of each product to minimize the loss/gain over time.
If you have products with random prices like lets say you are renting web servers and the price is $0.01/second. Then the expectation value for your loss/gain is close to zero. And the more purchases are made the closer to zero it gets. So you are not loosing anything here regardless of the approach. One time you win some one time you loose some.
In my opinion I would standardize it to round everything:
$price = 4.47;
$quantity = 1.2 // lets say liters
// Even round the price before applying tax
$totalPrice = round($price * $quantity, 2);
because if you are forced to show all the different stages of calculation then you will have to round every step.
But the most precise would be to use this as the least information is lost:
// Round once at end
$totalPrice = round($price*$quantity*$tax*$exchangeRate, 2);
In the end it all depends on how you set up your product prices or how your pricing works to be able to choose which method to go with. I'd say it doesn't really matter, I think every company simply chooses what suits them best.
Legally, some countries/cities/etc. have laws on how to calculate this, you should be looking at Great Britain laws to check on the valid procedure for your problem.
I can't tell you what the correct option is or even if there is one correct option. But from experience I can say, if there are multiple options to do one thing, make it configurable in your software. In this case you can easily use the strategy pattern and make the strategy for calculating prices configurable. Customers can choose how they want it calculated.
The correct solution depends on your business. When you sell items in different countries, you most likely have branches in those countries - and you need a net price in those country's currency. This results in the net price per item "translated" to the foreign currency, and this net price is then multiplied with the amount and multiplied with the tax factor/percentage).
The EU MOSS (which is charged when you offer services in other countries, or e.g. software as download) is somehow different. You can sell products with GBP pricing, but have to consider your consumer's local tax factor. See e.g. https://ec.europa.eu/taxation_customs/sites/taxation/files/resources/documents/taxation/vat/how_vat_works/telecom/one-stop-shop-guidelines_en.pdf
For MOSS, I didn't check in detail, but I expect that you then have a different formula, using your local GBP net price per item, multiply with amount, multiply with consumer's tax percentage. This tax amount, still in GBP, should then be multiplied with currency exchange rate, I'd expect.
I would like to calculate percentage of one of my measures.
For example:
I have a measure with aggregator distinct-count.
I would like to calculate the percentage of that measure, based on the current information.
For example: gender users-distinct-count percentage
male 25 25% (25/100)
female 41 41% (41/100)
unk 34 34% (34/100)
But, if I filter out unk, I want the percentage to be out of 25+41, i.e. 66
gender users-distinct-count percentage
male 25 37.8% (25/66)
female 41 %62.2 (41/66)
I also want, that when viewing the data with different dimensions, the total sum will be updated accordingly.
I tried this:
<CalculatedMember name="user_percentage" caption="Users Percentage"
formula="[Measures].user_count/ ([Measures].user_count,[dim1].[All Dim1],[dim2].[All Dim2])" dimension="Measures" visible="true">
</CalculatedMember>
but, when filtering values on the dimensions (like removing the
"unk", the total remains the same (over all dim).
Thanks,
You should do it at the client level, not the schema level.
The schema has no idea what you're querying on your rows or columns, only the client does.
Some client tools allow you to create a calculated measure as a % of the visible values, but that has to be done by the query.
Example:
With
SET ROWSET as {[Gender].[Male],[Gender].[Female]}
MEMBER [Gender].[Visible] as Aggregate( ROWSET, [Measures].[user_count] )
MEMBER [Measures].[Percentage] as ( [Measures].[user_count], [Gender].CurrentMember ) / ( [Measures].[user_count], [Gender].[Vislble] )
SELECT
ROWSET on Rows,
{ [Measures][user_count], [Measures].[Percentage] } on Columns
FROM [My Cube]
As you must reference the set selected on rows when defining the percentage, you cannot define it at the schema level.
I have two tables in my setup. One with sales persons and there income. Each sales person only know their total income. For this particular income period, they are asked to give an estimate of their income on either private, small business or large business customers. This information is entered in the second table.
Income
=================
SalesPerson
Income
Distribution
=============================
SalesPerson
CustomerType
Weight
Now, my query would look something like this:
SELECT
Income.SalesPerson,
Distribution.CustomerType,
Income.Income * Distribution.Weight as DistributedIncome
FROM
Income INNER JOIN Distribution ON
Income.SalesPerson = Distribution.SalesPerson
How would I enforce, that the SUM(Weight) = 1 for each SalesPerson in Distribution?
Normalize by the sum, according to the same criteria.
SELECT
Income.SalesPerson,
Distribution.CustomerType,
Income.Income * Distribution.Weight/(
select sum(d.weight)
from distribution d
inner join income i on i.salesperson = d.salesperson
)
as DistributedIncome
FROM
Income INNER JOIN Distribution ON
Income.SalesPerson = Distribution.SalesPerson
If somehow want to select unmodified weights that sum to 1 then I believe you've got a case of the subset sum problem and you are probably not going to be able to solve this with an SQL query.