DAX SUMX: Storing a filtered table in a VAR and reference its columns later on in the expression - ssas

In a measure (SUMX) I am filtering a table and storing it in a variable.
var currency = factFx[ALPHABETIC_CURRENCY_1]
var fxRates = FILTER(
factMarketDataExchangeRates;
factMarketDataExchangeRates[FX_CURRENCY] = currency
)
Then I need to do calcs that include further filtering fxRates
var exchangeRateOnTradeDate = CALCULATE(
[Measure];
FILTER(
fxRates;
fxRates[CURVE_DATE] = tradeDate
)
)
This throws an error in SSDT Cannot find table fxRates
Also It appears intellisense is not working. But each of the following does work. But is this expected behaviour?
Without table prefix:
var exchangeRateOnTradeDate = CALCULATE(
[Measure];
FILTER(
fxRates;
[CURVE_DATE] = tradeDate
)
)
With the underlying table's prefix:
var exchangeRateOnTradeDate = CALCULATE(
[Measure];
FILTER(
fxRates;
factMarketDataExchangeRates[CURVE_DATE] = tradeDate
)
)

Yes, this is the expected behavior. You can only use the table[COLUMN] syntax for tables in your data model.
Both of your working versions are equivalent to substituting in the definition of fxRates.
var currency = factFx[ALPHABETIC_CURRENCY_1]
var exchangeRateOnTradeDate =
CALCULATE (
[Measure];
FILTER (
FILTER (
factMarketDataExchangeRates;
factMarketDataExchangeRates[FX_CURRENCY] = currency
);
factMarketDataExchangeRates[CURVE_DATE] = tradeDate
)
)
Since [CURVE_DATE] ultimately derives from factMarketDataExchangeRates, using that table prefix is really what's happening under the hood, but you are allowed to use the other version where that table is abstracted away and doesn't clutter your code.
The important thing to remember is that the fxRates variable isn't actually a table in this case, but rather a semantic trick to write code more legibly.

Related

is it possible to store a table into a DAX variable conditionally

I'd like to store a table in a variable, but based on conditions of the visual.
e.g.
VAR ColumnValues = values( SpecificTable[SpecificColumn] )
works fine, but what I'd like to do is:
VAR ColumnValues = if([some condition T/F], values( SpecificTable1[SpecificColumn1] ) , SpecificTable2[SpecificColumn2] )
For reference, this question is in exploration of workarounds to solve question: Dynamic measure that responds to dynamic dimension which I marked as answered prematurely. I still do not have a solution to dynamically work with column values in DAX.
I've not been able to work out a syntax that allows this. Switch only returns scalar strings, and IF seems to only allow for a scalar result, not a table. Any other options I'm not thinking of?
Was not explicitly using any condition, but the condition that I was checking for, that I was able to get the desired result with the following:
Create Field Parameter (name it "_Dimension"), selecting the columns that need to be in play in the DAX
DAX looks like this:
VAR SelectedDim = SELECTEDVALUE( _Dimension[_Dimension Fields] ) //fully qualified - created by field parameter
//stage the values in each of the columns available
VAR Dim1Values = ADDCOLUMNS( VALUES( Dim1[Column1] ) , "RowValue" , Dim1[Column1] , "ColumnName" , "'Dim1'[Column1]" )
VAR Dim2Values = ADDCOLUMNS( VALUES( Dim1[Column2] ) , "RowValue" , Dim1[Column2] , "ColumnName" , "'Dim1'[Column2]" )
//... same pattern, as many column as needed
VAR SelectedDimValues = FILTER( UNION( Dim1Values, Dim2Values ) , [RowValue] = SelectedDim ) //return the values just for the selected column
SelectedDimValues is a Variable that contains a table with the rows from my selected dimension.

Linq Query in VB

Good Day,
I am querying my database using Linq and I have run into a problem, the query searched a column for a search phrase and based on if the column has the phrase, it then returns the results, The query is below,
Dim pdb = New ProductDataContext()
Dim query =
From a In pdb.tblUSSeries
Join b In pdb.tblSizes_ On a.Series Equals b.Series
Where
a.Series.ToString().Equals(searchString) Or
b.Description.Contains(searchString) Or Not b.Description.Contains(Nothing)
Order By b.Series, b.OrderCode Ascending
Select New CustomSearch With
{
.Series = a.Series,
.SeriesDescription= a.Description,
.Coolant = a.Coolant,
.Material = a.Material,
.Standard = a.Standard,
.Surface = a.Surface,
.Type = a.Type,
.PointAngle = a.PointAngle,
.DiaRange = a.DiaRange,
.Shank = b.Shank,
.Flutes = b.Flutes,
.EDPNum = b.EDPNum,
.SizesDescription = b.Description,
.OrderCode = b.OrderCode
}
Return query
I think the problem is that, in the table certain rows are NULL, so when it is checking the column for the phrase and it encounters a row that is null it, breaks and returns this error,
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
I have ran this query against another column that has all the rows populated with data and it returns the results ok.
So my question is how can I write it in VB to query the db with the supplied searchstring and return the results, when some of the rows in the columns have null values.
Any help would be great.
The exception occurs when you make the projection (i.e. select new CustomSearch)
And yes your trying to assign Null to some int property
(Not sure which one of your properties that is)
one of 2 choices :
1) Use nullalbe types for your properties (or just that one property).
2) project with an inline If ( ?? in C#) , I don't know VB so don't catch me on the syntax.
Taking Series just as an example i don't know if it's an int or if that's the problematic property
Select New CustomSearch With
{
.Series = If(a.Series Is Nothing,0, CInt(a.Series))
}
In C#
Select new CustomSearch
{
Series = a.Series ?? 0;
}

Using condition in Calculatetable ()

I've a problem on Table filtering while using CALCULATETABLE()
I tried to use the script with condition for CALCULATETABLE():
XeroInvoices[AmountPaid] < XeroInvoices[AmountDue]
EVALUATE
SUMMARIZE(
CALCULATETABLE(XeroInvoices,
XeroInvoices[Status] = "AUTHORISED",
XeroInvoices[DueDate] <= TODAY(),
XeroInvoices[AmountPaid] < XeroInvoices[AmountDue]
),
XeroInvoices[Number],
XeroInvoices[Reference],
XeroInvoices[Status],
XeroInvoices[Date],
XeroInvoices[DueDate],
XeroInvoices[AmountPaid],
XeroInvoices[AmountDue]
)
but the error that i get in DAX Studio is as following:
Query (6, 30) The expression contains multiple columns, but only a single column can be used in a True/False expression that is used as a table filter expression.
I managed only to kinda achieve that I wanted only like this -- crating new column within SUMMARIZE() syntax and later filtering it in Excel:
EVALUATE
SUMMARIZE(
CALCULATETABLE(XeroInvoices,
XeroInvoices[Status] = "AUTHORISED",
XeroInvoices[DueDate] <= TODAY()
),
XeroInvoices[Number],
XeroInvoices[Reference],
XeroInvoices[Status],
XeroInvoices[Date],
XeroInvoices[DueDate],
XeroInvoices[AmountPaid],
XeroInvoices[AmountDue],
"AmPaid<AmDue",XeroInvoices[AmountPaid]< XeroInvoices[AmountDue]
)
Does anyone know what might be the reason for this Err in CALCULATETABLE() and what might be a proposed solution?
Thanks!!
Check this
To filter by multiple columns you have to explicitly specify the "FILTER"
CALCULATETABLE (
Product,
FILTER (
Product,
OR ( Product[Color] = "Red", Product[Weight] > 1000 )
)
)

Nhibernate and like statement on XML field

I have a wrapped fluent nhibernate framework that I'm reusing and have no control over the actual mapping.
In my entity object I have a property mapped as string to an XML column in sql.
Hence when I run a query like:
var myResult = (from myTable in DataManager.Session.Query<Table>()
where myTable.thatXmlFieldWhichIsMappedAsString.Contains(AnXmlSnippet))
select myTable).FirstOrDefault();
It is trying to use the LIKE operator in SQL which is invalid on that column type.
How can I get around this without having to select all the rows and converting to List first?
In case, that we do not need .Query() (LINQ), and we can use Criteria query or QueryOver, we can use conversion:
// the projection of the column with xml
// casted to nvarchar
var projection = Projections
.Cast(NHibernateUtil.StringClob
, Projections.Property("thatXmlFieldWhichIsMappedAsString"));
// criteria filtering with LIKE
var criteria = Restrictions.Like(projection, "searched xml");
// query and result
var query = session.QueryOver<MyEntity>()
.Where(criteria)
;
var result = query
.SingleOrDefault<MyEntity>()
;
From my experience this could lead to conversion into small nvarchar(255) - sql server... Then we can do it like this:
var projection = Projections
.SqlProjection("CAST(thatXmlFieldWhichIsMappedAsString as nvarchar(max)) AS str"
, new string[]{}
, new NHibernate.Type.IType[]{}
);

How to execute query with subqueries on a table and get a Rowset object as a result in Zend?

I'm currently struggling on how to execute my query on a Table object in Zend and get a Rowset in return. Reason I need particularly THIS is because I'm modifying a code for existing project and I don't have much flexibility.
Query:
SELECT *
FROM `tblname` ud
WHERE ud.user_id = some_id
AND
(
(ud.reputation_level > 1)
OR
(
(SELECT COUNT( * )
FROM `tblname` t
WHERE t.user_id = ud.user_id
AND t.category_id <=> ud.category_id
AND t.city_id <=> ud.city_id
) = 1
)
)
Is there a way to describe this query using Select object?
Previous SQL solution was very simple and consisted of one WHERE clause:
$where = $this->getAdapter()->quoteInto("user_id = ?",$user_id);
return $this->fetchAll($where);
I need to produce same type of the result (so that it could be processed by existing code) but for more complicated query.
Things I've tried
$db = Zend_Db_Table::getDefaultAdapter();
return $db->query($sql)->fetchAll();
---------------- OR ----------------------
return $this->fetchAll($select);
---------------- OR ----------------------
return $this->_db->query($sql)->fetchAll();
But they either produce arrays instead of objects or fail with Cardinality violation message.
I would appreciate any help on how to handle SQL text queries in Zend.
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
//change the fetch mode becouse you don't like the array
$dbAdapter->setFetchMode(Zend_Db::FETCH_OBJ);
$sql = "you're long sql here";
$result = $dbAdapter->fetchAll($sql);
Zend_Debug::dump($result);
exit;
For a list of all fetch modes go to Zend_Db_Adapter
To write you're query using Zend_Db_Select instead of manual string , look at Zend_Db_Slect