I need to add an amount but with 2 conditions in the same column. (DAX PIVOT) - powerpivot

I need to add an amount but with 2 conditions in the same column.
For example:
Total Amount = product1 and product2
I'm trying something like this:
calculate(sum(amount]);filter([Column1]="product1" && [Column1]="product2"))

There is a fairly steep learning curve on some of the DAX basics but once you get past it then things get easier! Try this:
= CALCULATE(
SUM(mytable[amount]),
mytable[Column1] = "product1" ||
mytable[Column1] = "product2"
)

If you're looking to do an "AND" sum - so to only sum the amount when both criteria are present - you can use this:
=CALCULATE(
SUM(tablename[amount]),
tablename[Column1] = "Product1",
tablename[Column1] = "Product2")
The code is basically saying:
DO(
(This expression),
Filtering according to this expression,
Filtering according to this expression))
When you have more than one filter expression in the Calculate formula (separated by commas), DAX will treat it as an "AND" expression - i.e. it will do the expression only for those values which meet all the criteria you've set according to the filter contexts.
So here, your filter contexts are where Column 1 = Product 1 and where Column 1 = Product 2.
To expand on what Jacob said, once you "get" Calculate, things start making a lot more sense a lot quicker...

Related

DAX dynamic filter using two columns from related table

I need to make some simple calculation using DAX, but I am not sure how do I achieve same result as I did in Excel's formulas.
First of all my data structure looks as on screenshot:
Measures are coming from one table, and the PactDelivered is an attribute from related table which is connected by relationship.
All I really have to do is to translate formula as below into DAX:
There is no problem when it comes to calculate B3-C3-D3, but I have a problem how do I calculate the - B4 + C4 part. Of course it should be dynamic, so if it comes to calculate result for Package number 10, then it'd take figures from number 10 and 11.
EDIT:
After modification of code from Alexis Olson I got something like below, but it's not working yet. Please note the PactDelivered is in other table than measures are. Not knowing why, but it's calculating the result on packs according to NextPack value. I tried adding another variable which was basically NextPack -1, and tried calculating the sums from return using it, but didn't work as well.
Cancellations:=
var NextPack = MAX('Order'[PactDelivered]) + 1
var NextOrders = CALCULATE(SUM('Fact DropOff'[OrdersSentOut]) + sum('Fact DropOff'[OrdersReturned]), 'Order'[PactDelivered] = NextPack)
return SUM ('Fact DropOff'[OrdersSentOut]) - SUM ('Fact DropOff'[OrdersReturned] ) - SUM('Fact DropOff'[ActiveSubscriptions]) - NextOrders
EDIT2:
Sample data from fact:
From dimension:
Relationship:
Try a measure like this:
Measure =
VAR NextPact = MAX(Orders[PactDelivered]) + 1
VAR NextOrders = CALCULATE(SUM(Orders[OurdersSentOut]) - SUM(Orders[OrdersReturned]),
Orders[PactDelivered] = NextPact)
RETURN SUM(Orders[OurdersSentOut]) - SUM(Orders[OrdersReturned]) -
SUM(Orders[ActiveSubscriptions]) - NextOrders
First, we calculate the next index by taking the current index and adding 1. Then you calculate sent out minus returns for that index. Finally, subtract that from the current row calculation.

SQL - Loop through a list and add to a variable using sql select statements

I have data loaded in a table called Trades. Now I need to query this table, find elements that satisfy a particular condition and produce the trade value amount.
Here is the requirement
TradeAmt = 0
Loop for all Trades
{IF TradeId is 35
If type = 'I'
ADD (TradeAmt =TradeAmt + col_TradeAmt )
else
ADD (TradeAmt = TradeAmt + col_TradeAmtOverlap )
END-IF}
Return TradeAmt
Data:
Row1: tradeid=35, type=I, col_TradeAmt=10, col_TradeAmtOverlap=20
Row2: tradeid=35, type=S, col_TradeAmt=30, col_TradeAmtOverlap=40
Output: TradeAmt=50
How can i write this using SQL statements.
Well, in SQL you don't really loop over a sequence.
You write a statement that describes what you want to get from the set of data (e.g. the Trades table).
In your case, you want to accumulate all the elements in some way and provide that accumulation as a result, you can do that by using an aggregate function like SUM.
Something along these lines probably could work. Note that I'm nesting two queries here, the inner one to decide which column to treat as the "Amount" to accumulate depending on the Type of the trade and also to filter only the trade with Id 35, and the outer query performs the sum aggregate of all amounts:
SELECT SUM("Amount") FROM
(SELECT
CASE
WHEN Type = 'I' THEN col_TradeAmt
ELSE col_TradeAmtOverlap
END "Amount"
FROM Trades
WHERE TradeId = 35) "TradeAmt";

Questions on BETWEEN syntax

I'm working on a script which retrieves the latest balance for an account that is earlier or equal to a given date. For example, if the last movement of the account was on Jan.5, and I input Jan.8 on the script, it would have to retrieve the balance back in Jan.5 . of course, if there is any movement in the account on Jan.8, then it would retrieve the balance at Jan.8 . Each balance though, is valid for a given date range, as dictated by the columns BAL_DATE and END_BAL_DATE.
This script works, butI find it very unusual since the position of the values and the expressions are swapped:
SELECT
*
FROM
tbaadm.gstt
WHERE
gl_sub_head_code = '12403'
AND
crncy_code in ('USD','HKD')
AND
sol_id = 5001
AND
last_day('29-OCT-2015') BETWEEN BAL_DATE and END_BAL_DATE
Is it okay if I use this script? Or is it bad practice?
From the documentation,
BETWEEN Conditions
A BETWEEN condition determines whether the value of one expression is
in an interval defined by two other expressions.
Basically, you are comparing two expressions to an expression.
last_day('29-OCT-2015') BETWEEN BAL_DATE and END_BAL_DATE
In your query, you are comparing expr 1 i.e. last_day('29-OCT-2015') to expr 2 BAL_DATE and expr 3 END_BAL_DATE.
The entire BETWEEN condition is internally interpreted as:
last_day('29-OCT-2015') >= BAL_DATE AND last_day('29-OCT-2015') <= END_BAL_DATE
To answer your concern, note that in SQL, you can use multiple where clause by using and condition.
select ....
from ....
where <condition1>
and <condition2>
...
So the between query is correctly used. You can use between query in where clause and rest all in and and you will get exact same result. So your query is similar to
SELECT
*
FROM
tbaadm.gstt
WHERE
last_day('29-OCT-2015') BETWEEN BAL_DATE and END_BAL_DATE
and
gl_sub_head_code = '12403'
AND
crncy_code in ('USD','HKD')
AND
sol_id = 5001

MDX query: filter and sum of filtered

I've just started to learn MDX and i want to do a query like that:
filter data by the cost ( i've already made that query but without the sum) like that:
SELECT [Measures].[SumOfSelled] ON 0,
FILTER ([From].[From].[City].members, [Measures].[SumOfSelled]>7000) ON 1
FROM [BI-Avia]
It's working
and it is OK
BUT!!!
I need also to show the sum of filtered elements under this filtered result by cities
I know how to find it separately:
with member [Measures].FilteredSum as sum(filter([From].From].City].members,Measures].SunOfSelled]>7000),Measures].[SumOfSelled])
select{SumOfSelled} on 0
from [BI-AVIA]
But i have to show this together!! The SUM under Filtered! two in one! I need youe help! I think it's very clear for you!!!
Just define the calculated member on the [From].[From] hierarchy and then combine both queries, using a union of sets (abbreviated with + in MDX):
with member [From].[From].FilteredSum as
sum(filter([From].[From].City].members, Measures].SumOfSelled]>7000))
SELECT [Measures].[SumOfSelled]
ON 0,
FILTER ([From].[From].[City].members, [Measures].[SumOfSelled]>7000)
+
{ [From].[From].FilteredSum }
ON 1
FROM [BI-Avia]
You could possibly define the filter as a set in the WITH clause, which would avoid that Analysis Services evaluates it twice.

SQL Report Builder: get value from group within tablix

Please forgive the vague title of this question. Perhaps the below will ask my question better.
Consider the below aggregated table:
Fruit Units FruitSales%
----- ----- -----------
Apples 10 ?
Oranges 20 ?
Bananas 10 ?
NonFruit 10 ?
TOTAL 50 ?
I need the FruitSales% column to be: Fruit / (Total - NonFruit)
If NonFruit is a product name of its own, how do I get its value for use in other calculations in the tablix?
I imagine my formula for the FruitSales% is something like:
Sum(Fields!Units.Value) / (ReportItems!txtTotalUnits.Value - SumIf(Fields!Fruit = "NonFruit", Fields!Units.Value)
However, SumIf does not exist and even if it did, it would be specific to the current row.
And while I'm here, ReportItems!txtTotalUnits.Value, I have obviously named that text box, but is there a cleaner way to reference it?
Say the underlying DataSet (which I've called FruitDataSet) looks like this:
I've created a simple report based on this data:
The Fruit Sales % expression is:
=Sum(IIf(Fields!fruit.Value <> "NonFruit", Fields!units.Value, 0))
/ Sum(IIf(Fields!fruit.Value <> "NonFruit", Fields!units.Value, 0), "FruitDataSet")
This gives what I think is the correct results:
There are two things to note about the expression:
By running the Sum against an IIf expression, you can control what gets included in the totals - here I'm setting NonFruit explicitly to 0.
By setting the Scope of the aggregate expression, you can get overall totals to use to work out total percentages - in the report I'm getting a total using FruitDataSet and comparing this to the group-level total to get a % value.
The way you're referencing the textbox total is fine; the only other option would be to use an expression each time you want the total - if this is outside a Tablix you would need to explicitly set the Scope, e.g. the DataSet.