简体   繁体   中英

How to join 2 tables in Power BI with condition involving a 3rd table

I have 3 tables, Company, Address and C_detail. I need to count how many company with a certain C_ID from the C_detail table. But the relation existed are Company(CompanyID)=Address(CompanyID), Address(CountryID)=C_detail(CountryID). To be exact I need to translate this sql into Power BI.

SELECT COUNT (*)
FROM Company a
JOIN Address b ON a.CompanyID = b.CompanyID
WHERE b.CountryID IN ( SELECT CountryID from C_detail WHERE C_ID = '1')

How I join the tables with applying condition from different table? Thanks and note that I am actually quite new with DAX so really appreciate a very clear explanation on this.

The best way is to create the relationships between those 3 tables in powerBI (set the filter to both directions):

Company to Address on CompanyID
Address to C_detail on CountryID

Then you can create a simple measure COUNT(Company[CompanyID]) and use a slicer with the values of C_ID

If you don't want to or can't create the relationships, you can probably achieve a similar result with the following measure:

CompanyCount= 
VAR tbl =
    SELECTCOLUMNS (
        FILTER (
            SUMMARIZE (
                'Address',
                'Address'[CompanyID],
                "valid",
                    CALCULATE (
                        COUNTROWS ( 'Address' ),
                        TREATAS ( VALUES ( 'Detail'[CountryID] ), 'Address'[CountryID] )
                    )
            ),
            [valid] > 0
        ),
        "CompanyID", 'Address'[CompanyID]
    )
RETURN
    CALCULATE ( COUNTROWS ( 'Company' ), TREATAS ( tbl, 'Company'[CompanyID] ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM