Forum Discussion

knotpc's avatar
knotpc
Advocate I
10 years ago

Searching between two columns for a value within a range (Zip Code)?

Hello, 

 

As I begin to migrate from Excel to Power BI, because the office loves the reports :), I keep getting stuck trying to identify formulas that will work in DAX. What a learning curve :). 

 

Anyway, I have a table with customer account information. One column has the customers zipcode, which I have stored as text to support international customers. I have a second table that has three columns. StartZipCode, EndZipCode and RepFirm. In the account table I have created a calculated column call RepFirm. In the calcuated column I put the following formula:

 

RepFirm = IF(Accounts[Sales Region]="US",IFERROR(LOOKUPVALUE(USRepRegions[REP_NAME],USRepRegions[FROM_ZIP],Accounts[Postal Code]),"UNK"),"UNK")

 

The code above looks through the beginning zip codes and looks for an exact match :(. I am used to using VLOOKUP and looking for values accross columns and within a range. For example VLOOKUP would use Postal Code 30101 and go to the ZipCode table and find that 30101 is between columns ToZip 30000 and FromZip 32000 and return the rep firm. See example lookup table below.

 

FROM_ZIPTO_ZIP
0600
601987
988999
10002799
28002999
30003899
39004999
50005999
60006999
70008999
90009999
1000011999
1200012399
1240012699
1270012799
1280014999
1500016899
1690019699
1970019999
2000020599
2060021299
2130021399
2140021999
2200024699
2470026999
2700028999
2900029999
3000031999
3200032399
3240032599
3260034999
3500036999
3700038599
3860039799
3980039999

 

Any help or ideas on how to solve this would be greatly appreciated. 

2 Replies

  • chrisu's avatar
    chrisu
    Responsive Resident

    One way I can think to make this work, which may or may not work with what you need to accomplish, would be to recreate your zip code ranges table to include every possible unique zip code.  This works well within PowerBI's preferred many-rows-few-columns structure, and Zip then becomes a unique identifier that you can connect to the zips in the customer table (a one-to-many relationship).   So instead of StarZip, EndZip, and RepFirm, you would have two columns:

     

    Zip    RepFirm

    0       Firm A

    1       Firm A

    2       Firm A

    3       Firm B

    4       Firm B

    .....     .....

     

    You could also include columns for "ZipRange", "ZipStart", or "ZipEnd" if you need them.  Then all you have to do is create a relationship between the customer account table Zip column and the ZipCode table zip column and RepFirm will automatically be matched up with the customer.  That would save some formula writing.