POWER BI - DAX - Measure filter - sql-server

I have a dax measure . This measure have 1 data . This is "GOOGLE";"YOUTUBE";"AMAZON"
I want to use this 1 line string result in FILTER.
CALCULATE(SUM(_TABLE);_TABLE.COMPANIESNAME; FILTER(_TABLE.COMPANIESNAME IN { mymeasure } ))
Does anyone can help me solve this problem ?
Thank you for help

There are probably way better ways to do what you want. You are treating Power BI like a relational database when you should be using it like a Star Schema. But without more info, I'm just going to answer the question.
Here's my sample table:
// Table
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcsxNrMrPU9JRMlSK1YlWcs/PT89JBXKNwNzI/NKQ0iQQ3xjMd0tMTk3Kz88GCpgoxcYCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Company = _t, Count = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Count", Int64.Type}})
in
#"Changed Type"
I don't have your DAX measure or its name, so I'm using this:
CompanyList = """Google"";""YouTube"";""Amazon"""
Just to prove it's the same as your measure, here it is in the report:
From this post I created a DAX formula that will parse your DAX value into a table with one row for each company name. Add this as a DAX table from Modeling > New Table. I named mine "Filtered table".
Filtered table = VAR CommaSeparatedList = [CompanyList]
VAR BarSeparatedList =
SUBSTITUTE ( CommaSeparatedList, ";", "|" )
VAR Length =
PATHLENGTH ( BarSeparatedList )
VAR Result =
SELECTCOLUMNS (
GENERATESERIES ( 1, Length ),
"Company", SUBSTITUTE( PATHITEM ( BarSeparatedList, [Value] ), """", "")
)
RETURN
Result
Here's what the table looks like:
Add a relationship between the two tables like this (Modeling > Manage relationships > New...):
Then add a DAX column to the filtered table by selecting the table and then Modeling > New Column
Count = CALCULATE(SUM('Table'[Count]))
You can total it up with this DAX measure:
Filtered total = SUM('Filtered table'[Count])
Change the CompanyList measure, and result will update:

Related

How to Improve the ADO Lookup Speed?

I write a C++ application via Visual Studio 2008 + ADO(not ADO.net). Which will do the following tasks one by one:
Create a table in SQL Server database, as follows:
CREATE TABLE MyTable
(
[S] bigint,
[L] bigint,
[T] tinyint,
[I1] int,
[I2] smallint,
[P] bigint,
[PP] bigint,
[NP] bigint,
[D] bit,
[U] bit
);
Insert 5,030,242 records via BULK INSERT
Create an index on the table:
CREATE Index [MyIndex] ON MyTable ([P]);
Start a function which will lookup for 65,000,000 times. Each lookup using the following query:
SELECT [S], [L]
FROM MyTable
WHERE [P] = ?
Each time the query will either return nothing, or return one row. If getting one row with the [S] and [L], I will convert [S] to a file pointer and then read data from offset specified by [L].
Step 4 takes a lot of time. So I try to profile it and find out the lookup query takes the most of the time. Each lookup will take about 0.01458 second.
I try to improve the performance by doing the following tasks:
Use parametered ADO query. See step 4
Select only the required columns. Originally I use "Select *" for step 4, now I use Select [S], [L] instead. This improves performance by about 1.5%.
Tried both clustered and non-clustered index for [P]. It seems that using non-clustered index will be a little better.
Are there any other spaces to improve the lookup performance?
Note: [P] is unique in the table.
Thank you very much.
You need to batch the work and perform one query that returns many rows, instead of many queries each returning only one row (and incurring a separate round-trip to the database).
The way to do it in SQL Server is to rewrite the query to use a table-valued parameter (TVP), and pass all the search criteria (denoted as ? in your question) together in one go.
First we need to declare the type that the TVP will use:
CREATE TYPE MyTableSearch AS TABLE (
P bigint NOT NULL
);
And then the new query will be pretty simple:
SELECT
S,
L
FROM
#input I
JOIN MyTable
ON I.P = MyTable.P;
The main complication is on the client side, in how to bind the TVP to the query. Unfortunately, I'm not familiar with ADO - for what its worth, this is how it would be done under ADO.NET and C#:
static IEnumerable<(long S, long L)> Find(
SqlConnection conn,
SqlTransaction tran,
IEnumerable<long> input
) {
const string sql = #"
SELECT
S,
L
FROM
#input I
JOIN MyTable
ON I.P = MyTable.P
";
using (var cmd = new SqlCommand(sql, conn, tran)) {
var record = new SqlDataRecord(new SqlMetaData("P", SqlDbType.BigInt));
var param = new SqlParameter("input", SqlDbType.Structured) {
Direction = ParameterDirection.Input,
TypeName = "MyTableSearch",
Value = input.Select(
p => {
record.SetValue(0, p);
return record;
}
)
};
cmd.Parameters.Add(param);
using (var reader = cmd.ExecuteReader())
while (reader.Read())
yield return (reader.GetInt64(0), reader.GetInt64(1));
}
}
Note that we reuse the same SqlDataRecord for all input rows, which minimizes allocations. This is documented behavior, and it works because ADO.NET streams TVPs.
Note: [P] is unique in the table.
Then you should make the index on P unique too - for correctness and to avoid wasting space on the uniquifier.

Removing Blank Days from Power BI Chart

I have created a weekly request measure like so :
RequestsWeekly = var result= CALCULATE(
DISTINCTCOUNTNOBLANK(SessionRequests[RequestDateTime]),
FILTER('Date','Date'[WeekDate]=SELECTEDVALUE('DateSelector'[WeekDate],MAX('DateSelector'[WeekDate]))))+0
RETURN
IF ( NOT ISBLANK ( result ), result)
DateSelector is a standalone table (not connected to any other table in data model) that I have created for all the dates for a dropdown menu select for a Power BI Dasbboard. Unfortunately as there are less dates in the Date Selector table than the Date table, I get ...
Date table is the standard DATE table full of dates from 1970 to 2038. Date connects to Session Requests via a many to one relationships, single way filter. Session Requests is the main fact table.
I need to get rid of the blank row in my result set via DAX so it does not appear in my chart on the X axis. I have tried lots of different DAX combos like blank () and NOT ISBLANK. Do I need to create a table for the result set and then try to filter out the blank day there?
You should not check if the result is empty but if the VALUE ( Table[DayNameShort] ) exists for your current row context:
RequestsWeekly =
VAR result =
CALCULATE (
DISTINCTCOUNTNOBLANK ( SessionRequests[RequestDateTime] ),
FILTER (
'Date',
'Date'[WeekDate]
= SELECTEDVALUE (
'DateSelector'[WeekDate],
MAX ( 'DateSelector'[WeekDate] )
)
)
) + 0
RETURN
IF (
NOT ISBLANK (
VALUE ( Table[DayNameShort] ) -- put here correct table name
),
result
)

Enterprise Architect - how to extract nullability of a database table column?

I have a database table defined in EA. In this table I have a column where NULL is allowed. When I use a script or an API to extract nullability from this column, I understand this should be done using the LowerBound and UpperBound values. When LowerBound is 0, it is a nullable field, if it is 1, NULL is not allowed.
However, when I set the NULL field, LowerBound is still 1, as noted on the following picture:
How can I correctly extract nullability from a database column?
You have to look into Attribute.AllowDuplicates or t_attribute.AllowDuplicates (well, it's EA).
There seem to be two ways of retrieving that information:
Via SQL
Via API
Extending your example I defined to additional columns: NotNullAttribute and NullAttribute as shown in the figure below:
Now you get the results shown below when querying the element and its attributes:
LINQ and SQL query showing nullable columns:
SELECT *
FROM
[t_attribute] [t]
WHERE
[t].[Name] LIKE '%NullAttribute%'
Script for showing database table columns attributes:
function main(id)
{
var element AS EA.Element;
element = Repository.GetElementByID(id);
var attributes AS EA.Collection;
attributes = element.Attributes;
for(var c = 0; c < attributes.Count; c++)
{
var attribute AS EA.Attribute;
attribute = attributes.GetAt(c);
Session.Output(attribute.Name + ": " + attribute.AllowDuplicates);
}
}
main(18365);
// Output
/*
Id: true
Name: false
CustomerTypeEnumId: true
NotNullAttribute: true
NullAttribute: false
*/

Power Pivot: DAX for Same Value Sequential Count

Please reference the following example table.
The actual table would be contained in PowerPivot.
There are multiple runs identified by sequential numbering.
Based on what we want to observe through filtering, each run has an associated value.
Here's simplified version of the current data:
Current Table
Common Columns for all Data:
Part: Uniquely defines the group. In this case, it's part or device.
Run: Identifies a same test count.
Value: The outcome generated from the test.
What I've been trying to add is an additional three columns:
Desired1: Same_Value_Count: This counts consecutive same values.
Desired2: Same_Max: Gives the maximum same value count.
Desired3: Same_Min: Give the minimum same value count.
This would result in the following PivotTable:
Resulting Table
I am having trouble formulating the proper DAX syntax to accomplish the two extra columns.
Keep in mind, I'd like to show the whole table as is.
I have a calculated column here called count_seq_dup:
=CALCULATE(COUNTROWS(table), ALLEXCEPT(table, table[3_Value]), EARLIER(Table[2_Run]) >= CSVsource[2_Run])
It worked perfectly for a single part, but does not work with multiple parts parts and when other filtering or slicers are applied.
I'm close, but it's not exactly what I'm looking for, and I can't figure out the syntax in DAX to get it right.
Can anyone help me?
For the Same_Value_Count, try something like this:
Same_Value_Count =
VAR part = 'table'[1_Part]
VAR val = 'table'[3_Value]
VAR run = 'table'[2_Run]
VAR tblpart = FILTER ( 'table', 'table'[1_Part] = part && 'table'[2_Run] <= run )
RETURN
run - CALCULATE ( MAX ( 'table'[2_Run] ), FILTER ( tblpart, [3_Value] <> val ) )
This will return the maximum same value count for a part / value combination.
Max Count =
VAR part = 'table'[1_Part]
VAR val = 'table'[3_Value]
RETURN
CALCULATE (
MAX ( 'table'[Same_Value_Count] ),
FILTER ( 'table', [3_Value] = val && 'table'[1_Part] = part )
)

lambda expression for a query on two tables that returns records from one table

I have two tables
TableA (articles)
int id
int Type
string name
and
TableB (compatibles)
int linked_ID
int tableA_ID
TableA records:
id=1, Type=0, name="ArticleA"
id=2, Type=1, name="ArticleB"
id=3, Type=2, name="ArticleC"
id=4, Type=1, name="ArticleD"
TableB records:
linked_ID= 1, tableA_ID=2
linked_ID= 1, tableA_ID=3
linked_ID= 1, tableA_ID=4
TableB has a list of arcicels that are compatible to a certain article. I am quite new to queries (didn't need them in my projects yet). But as C# and WPF allow some pretty cool automation with Binding I would like to add a binding that returns the following:
Give me all articles that are of Type 1 and compatible to my selected article (id=1).
The simple part of it works well (articles has a list of all articles):
private ObservableCollection<Article> _articles =
new ObservableCollection<Article>();
[fill it with the available articles]
and then:
comboBoxArticles.ItemsSource =
_articles.AsBindable().Where( c => c.Typ == 0 );
How can I extend the Where clause to query another table?
Thanks a lot in advance.
It appears as if you want to "join" two "tables" using Linq. Here is something to get you started:
comboBoxArticles.ItemsSource =
from article in _articles
from compatible in _compatibles
where article.Type == 0 && && article.id == compatible.tableA_ID && compatible.linked_ID == 1
select article;
... or in method chain...
comboBoxArticles.ItemsSource = _articles
.SelectMany(article => _compatibles, (article, compatible) => new {article, compatible})
.Where(#t => #t.article.Type == 0 && #t.article.id == #t.compatible.tableA_ID && #t.compatible.linked_ID == 1)
.Select(#t => #t.article);

Resources