Search code examples
powerbidaxreportpowerquerypowerbi-desktop

Power bi returning value based on multiple condition


I have the data below

create table #data (Post_Code varchar(10),  Internal_Code varchar(10))
insert into #data values
('AB10','hb3'),('AB10','hb25'),('AB12','dd1'),('AB15','hb6'),('AB16','aa4'),('AB16','hb7'),
('AB16','aa2'),('AB16','ab9'),('AB18','rr6'),('AB18','rr9'),('AB18','hb10'),('AB20','rr15'),
('AB20','td2'),('AB21','hb8'),('AB21','cc4'),('AB21','cc4'),('AB24','td5'),('AB9','yy3'),
('RM2','CC1'),('RM6','hb6'),('RM7','cc2'),('SA24','rr1'),('SA24','hb5'),('SA24','rr2'),
('SA24','cc34'),('SE15','rr9'),('SE15','rr5'),('SE25','rr10'),('SE25','hb11'),('SE25','rr8'),
('SE25','rr1'),('LA15','rr2')

select * from #data
drop table #data

What I want to achieve is if the same post code area have “hb” or “rr” in the same post code I want to return 1 else 0 The “hb” or “rr” internal_code must be in the same post_code if they in different post code. It should be 0

I wrote this DAX

Result = IF(left(Data[Internal_Code],2)="hb" || left(Data[Internal_Code],2)="rr",1,0)

it is not returning the correct result

current output

enter image description here

expected output

enter image description here


Solution

  • I think your expected result is incorrect as SA24 should also be 1. You should definitely do a calculation like this in PQ but if you need to do it in DAX in a calculated column, then use the following code which works.

    Result = 
    
    VAR post_code = Data[Post_code]
    
    RETURN
    
    VAR hb = CALCULATE (COUNTROWS(Data),'Data'[Post_code] = post_code && left(Data[Internal_Code],2) = "hb" )
    VAR rr = CALCULATE (COUNTROWS(Data),'Data'[Post_code] = post_code && left(Data[Internal_Code],2) = "rr" ) 
    
    RETURN IF(hb>0 && rr > 0,1)
    

    enter image description here