Power BI - SQL query with Case When to DAX? - powerbi

I am trying to convert a below SQL query into DAX on my Power BI Report.
SQL QUERY: -
select Date
,Id
,MAX(CASE WHEN fkid = 1 then 1 else 0 end) as rflag
,MAX(CASE WHEN fkid = 128 then 1 else 0 end) as dflag
,CASE WHEN MAX(CASE WHEN fkid = 1 then 1 else 0 end) = 1 AND MAX(CASE WHEN fkid = 128 then 1 else 0 end)=1 THEN 1 ELSE 0 END AS BOTH
from table
GROUP BY Date,Id
INPUT TABLE: -
DATE ID FKID
09-07-2021 1 1
09-07-2021 1 128
09-07-2021 2 1
09-07-2021 3 128
10-07-2021 4 1
10-07-2021 4 128
10-07-2021 1 1
10-07-2021 1 128
FINAL OUTPUT :-
DATE FKID RFLAG DFLAG BOTH
09-07-2021 1 1 1 1
09-07-2021 2 1 0 0
09-07-2021 3 0 1 0
10-07-2021 1 1 1 1
10-07-2021 4 1 1 1
i have try to implement following dax query.
DAX: -
TEMTABLE =
GROUPBY(
TABLE,
TABLE[DATE],
TABLE[FKID],
"rflag", MAXX(CURRENTGROUP(),CALCULATE(TABLE,TABLE[fkID]=1),
"dflag", MAXX(CURRENTGROUP(),CALCULATE(TABLE,TABLE[fkID]=128),
"both", MAXX(MAXX([rflag])=1 AND MAXX([dflag])=1)
)

PowerQuery solution:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMrDUNTDXNTIwMlTSUYLgWB1swkYWmBJG2NUbI6k3NECSMIGrxxTGpt4Qu3q4e2IB", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [DATE = _t, ID = _t, FKID = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"DATE", type date}, {"ID", Int64.Type}, {"FKID", Int64.Type}}),
#"Added Custom" = Table.AddColumn(#"Changed Type", "rflag", each if [FKID] = 1 then 1 else 0),
#"Added Custom1" = Table.AddColumn(#"Added Custom", "dflag", each if [FKID] = 128 then 1 else 0),
#"Grouped Rows" = Table.Group(#"Added Custom1", {"DATE", "ID"}, {{"rflag", each List.Max([rflag]), type number}, {"dflag", each List.Max([dflag]), type number}}),
#"Added Custom2" = Table.AddColumn(#"Grouped Rows", "both", each if ( [rflag] = 1 and [dflag] = 1 ) then 1 else 0)
in
#"Added Custom2"
DAX solution:
Table 2 =
ADDCOLUMNS (
SUMMARIZE (
'Table' ,
'Table'[DATE], 'Table'[ID],
"rflag", IF ( CONTAINS ( 'Table', 'Table'[FKID] , 1 ) , 1 , 0 ),
"dflag", IF ( CONTAINS ( 'Table', 'Table'[FKID] , 128 ) , 1 , 0 )
),
"both", IF ( [dflag] = 1 && [rflag] = 1 , 1 , 0 )
)

Related

Ranking Averages by Criteria

here is the deal... (actually I've solved it but I am sure there is an easier way)
my table is :
Department ID
Criteria 1
Criteria 2
Criteria 3
DEP 001
4
5
3
DEP 002
5
5
5
DEP 003
3
4
5
DEP 004
2
3
5
DEP 001
4
4
5
DEP 003
1
2
4
DEP 002
2
2
4
DEP 003
3
5
2
DEP 002
5
2
5
DEP 005
4
3
1
DEP 001
1
5
3
DEP 002
2
1
2
DEP 003
4
2
5
DEP 005
3
4
1
DEP 002
5
5
4
DEP 005
1
2
2
DEP 001
2
3
1
DEP 002
3
1
5
I am trying to find the top 1 average in each criteria.
I've used unpivot, creating new table and then calculated column to find the result.
First Unpivoting
let
Source = YourTableName,
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Department ID", type text}, {"Criteria 1", Int64.Type}, {"Criteria 2", Int64.Type}, {"Criteria 3", Int64.Type}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Department ID"}, "Attribute", "Value")
in
#"Unpivoted Other Columns"
Second calculated Table :
Max Avg =
VAR _cr1 =
SUMMARIZE (
'YourTableName (unpivoted)',
'YourTableName (unpivoted)'[Department ID],
'YourTableName (unpivoted)'[Attribute],
"Criteria Avg",
CALCULATE (
AVERAGE ( 'YourTableName (unpivoted)'[Value] ),
ALLEXCEPT (
'YourTableName (unpivoted)',
'YourTableName (unpivoted)'[Department ID],
'YourTableName (unpivoted)'[Attribute]
)
)
)
RETURN
_cr1
and finally the calculated rank column and filter by 1
RANK =
RANKX (
FILTER (
'Max Avg',
'Max Avg'[Attribute] = EARLIER ( 'Max Avg'[Attribute])
),
'Max Avg'[Criteria Avg],
,
DESC,
DENSE
)
expected result is :
Can you suggest an easier way ?
This is PBix file where you can work on to suggest a faster way
Only by creating a couple of complicated measures. BTW, I'd always reshape data in PQ rather than DAX. Here is an alternative:
Create a criteria table.
Create a measure:
Attribute =
VAR a = ADDCOLUMNS(
SUMMARIZE(YourTableName, YourTableName[Department ID]) ,
"#crit1", CALCULATE(AVERAGE(YourTableName[Criteria 1])),
"#crit2", CALCULATE(AVERAGE(YourTableName[Criteria 2])),
"#crit3", CALCULATE(AVERAGE(YourTableName[Criteria 3]))
)
return
SWITCH(SELECTEDVALUE(Criteria[Criteria]),
"Criteria 1", MAXX(a, [#crit1]),
"Criteria 2", MAXX(a, [#crit2]),
"Criteria 3", MAXX(a, [#crit3])
)
Add to a table visual
Result

PowerBI - unpivot selected values from column

I have a table which has a list of Id's and categories. See below:
id
Category
Value
1
Pref 1 Region
MTO
1
Pref 1 Area
MT99
1
Pref 1 Station
ST124
1
Pref 2 Region
MTO
1
Pref 2 Area
MT85
1
Pref 2 Station
ST420
1
Pref 3 Region
BSW
1
Pref 3 Area
BS88
1
Pref 3 Station
ST876
2
Pref 1 Region
GRT
2
Pref 1 Area
GT34
2
Pref 1 Station
STT555
2
Pref 2 Region
MTO
2
Pref 2 Area
MT99
2
Pref 2 Station
ST124
2
Pref 3 Region
BSW
2
Pref 3 Area
BS88
2
Pref 3 Station
ST876
I want to keep the Pref # Station and 'unpivot' the other categories Area and Region to separate columns, like below:
id
Category
Value
Region
Area
1
Pref 1 Station
ST124
MTO
MT99
1
Pref 2 Station
ST420
MTO
MT85
1
Pref 3 Station
ST876
BSW
BS88
2
Pref 1 Station
STT555
GRT
GT34
2
Pref 2 Station
ST124
MTO
MT99
2
Pref 3 Station
ST876
BSW
BS88
I've tried unpivoting columns in PowerQuery but the order isn't kept. Any help is much appreciated!
This will produce the 2nd table:
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"id", Int64.Type}, {"Category", type text}, {"Value", type text}}),
    #"Split Column by Delimiter" = Table.SplitColumn(#"Changed Type", "Category", Splitter.SplitTextByEachDelimiter({" "}, QuoteStyle.Csv, true), {"Category.1", "Category.2"}),
    #"Pivoted Column" = Table.Pivot(#"Split Column by Delimiter", List.Distinct(#"Split Column by Delimiter"[Category.2]), "Category.2", "Value"),
    #"Unpivoted Columns" = Table.UnpivotOtherColumns(#"Pivoted Column", {"id", "Category.1", "Region", "Area"}, "Attribute", "Value"),
    #"Merged Columns" = Table.CombineColumns(#"Unpivoted Columns",{"Category.1", "Attribute"},Combiner.CombineTextByDelimiter(" ", QuoteStyle.None),"Category"),
    #"Reordered Columns" = Table.ReorderColumns(#"Merged Columns",{"id", "Category", "Value", "Region", "Area"})
in
    #"Reordered Columns"

How to filter table by two columns

I have the following table:
ID
TEST_ID
Component
ComponentInfo
1
5
Test 1
Info
2
5
Test 1
AB 2
3
5
Test 1
XY
4
5
Test X
Info 2
5
5
Test X
Info 1
6
5
Test Y
Info 2
7
6
Test 1
Info 2
8
7
ABC
Info 1
9
8
XYZ
Info 2
9
9
XYZ
Info 2
I like to get the following output:
TEST_ID
Component
5
Test 1
5
Test X
5
Test Y
6
Test 1
7
ABC
8
XYZ
9
XYZ
I think it would be nice to realize it in the data transformation part. How can I do that?
I don't see any filtering in your "question"; Rather, removing redundant columns and leaving unique values.
M language statement:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIF4pDU4hIFEMczLy1fKVYnWskIXcbRScEILGOMLhMRCRY3QRaPgJoF1WOKVc4QLGeGLBeJqs8cyDVDdx9UzgLINQc7zBnVQEsg1wLsrihUHSAJSwyJWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t, TEST_ID = _t, Component = _t, ComponentInfo = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"TEST_ID", Int64.Type}, {"Component", type text}, {"ComponentInfo", type text}}),
#"Removed Columns" = Table.RemoveColumns(#"Changed Type",{"ID", "ComponentInfo"}),
#"Removed Duplicates" = Table.Distinct(#"Removed Columns")
in
#"Removed Duplicates"
Press strg select TEST_ID and Component, right click then remove duplicates
= Table.Distinct(#"changed type", {"TEST_ID", "Component"})
Thats what I need! :-)

Power Bi: Calculate sum of columns month wise in other table

I have the leave data of a company.
Here is the sample data:
STAFF PL CL ML SP LWP TL Month
A 1 2 0 0 6 9 April
B 14 0 4 0 0 18 April
A 1 2 0 0 1 4 May
B 1 0 4 0 0 5 May
A 1 2 0 0 2 5 June
B 2 0 4 0 0 6 June
I want to transform this data into a table structure like this-
Here is the sample data:
Types of Leave Count Month
ML 89 4
CL 114 4
LWP 17 4
PL 135 4
SP 89 4
ML 89 5
CL 114 5
LWP 17 5
PL 135 5
SP 89 5
ML 89 6
CL 114 6
LWP 17 6
PL 135 6
SP 89 6
Can it be possible using SelectColumns, Summarizecolumn dax functions?
I tried --
SUMMARIZE(Table1, Table1[CL],Table1[LWP],Table1[ML],Table1[PL],"CL2", SUM(Table1[CL]), "ML2", SUM(Table1[ML]), "LW2P",SUM(Table1[LWP]), "P2L", SUM(Table1[PL]))
It just gave me weird results.
Unpivot the data after removing the name and the staff columns. Then convert the month name to the month number and build a pivot table.
The screenshot shows the result in Excel, but the same can be done in Power BI.
Here is the M code for the query as it was recorded when I clicked the ribbon icons:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"STAFF", type text}, {"PL", Int64.Type}, {"CL", Int64.Type}, {"ML", Int64.Type}, {"SP", Int64.Type}, {"LWP", Int64.Type}, {"TL", Int64.Type}, {"Month", type text}}),
#"Removed Columns" = Table.RemoveColumns(#"Changed Type",{"STAFF", "TL"}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Removed Columns", {"Month"}, "Attribute", "Value"),
#"Renamed Columns" = Table.RenameColumns(#"Unpivoted Other Columns",{{"Attribute", "Type of Leave"}, {"Value", "Count"}}),
#"Added Custom" = Table.AddColumn(#"Renamed Columns", "Custom", each Date.FromText([Month]&"1 2017")),
#"Extracted Month" = Table.TransformColumns(#"Added Custom",{{"Custom", Date.Month}}),
#"Removed Columns1" = Table.RemoveColumns(#"Extracted Month",{"Month"}),
#"Renamed Columns1" = Table.RenameColumns(#"Removed Columns1",{{"Custom", "Month"}})
in
#"Renamed Columns1"

PowerBI - Remove Initial Records with 0 values

I have a table in PowerBI that looks like this:
Date StoreID Car Sales <Row Num (for explanation only)>
1/1/2017 1 0 1
1/2/2017 1 0 2
1/3/2017 1 0 3
1/4/2017 1 20 4
1/5/2017 1 13 5
1/6/2017 1 0 6
1/7/2017 1 31 7
1/4/2017 2 0 8
1/5/2017 2 0 9
1/6/2017 2 7 10
1/7/2017 2 0 11
1/8/2017 2 10 12
What I am trying to do is create a measure that will calculate Car Sales by day (so on a line chart with Date on the x-axis), but eliminate the rows/records with 0's until the first Date that has a Sales value. In other words, I want to eliminate rows 1, 2, and 3, but not eliminate row #6, because that is a legitimate day where there were no cars sold. I also want to do this for every StoreID, so I want to eliminate rows 8 and 9, but not 11. Is there any way to come up with a measure/column (or other means) that will accomplish this in PowerBI?
You can group by StoreID, and then transform each column with: sort by [Date], then use Table.Skip to remove rows where [Car Sales] is 0. (Sorting by [Date] might not seem necessary, but group by can change ordering.) Then expand out the grouped tables.
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Date", type datetime}, {"StoreID", Int64.Type}, {"Car Sales", Int64.Type}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"StoreID"}, {{"Grouped", (grouped) => let
#"Sorted Rows" = Table.Sort(grouped,{{"Date", Order.Ascending}}),
SkipNoCarSales = Table.Skip(#"Sorted Rows", each [Car Sales] = 0)
in
SkipNoCarSales, type table}}),
#"Expanded Grouped" = Table.ExpandTableColumn(#"Grouped Rows", "Grouped", {"Car Sales", "Date"}, {"Car Sales", "Date"}),
#"Reordered Columns" = Table.ReorderColumns(#"Expanded Grouped",{"Car Sales", "StoreID", "Date"})
in
#"Reordered Columns"