Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124

當你需要用 兩個欄位的組合 才能唯一對應另一個表的紀錄(也就是 複合鍵關聯),Power BI 的「模型關聯」介面本身不支援直接用多欄位建立關聯。但有幾種方法可以達成相同效果
原理:在兩個表都建立一個新的「組合欄位」,用 & 將多個欄位串起來,然後用這個新欄位作為關聯鍵。
步驟:
假設有兩個表:
CustomerID, ProductIDCustomerID, ProductID你想要根據 CustomerID + ProductID 建立關聯。
CompositeKey = TableA[CustomerID] & "-" & TableA[ProductID]2. 在 TableB 同樣新增一個:
CompositeKey = TableB[CustomerID] & "-" & TableB[ProductID]3. 在「模型檢視」中,用這兩個 CompositeKey 欄位建立關聯。
CompositeKey = FORMAT(TableA[CustomerID], "0000") & "-" & FORMAT(TableA[ProductID], "0000")小技巧:
如果欄位是數字型別,最好先轉成文字再串接:
當你有多對多或需要彈性關聯時,可以建立一個「橋接表」。
例如:
建立一個新表(可用 DAX 建立):
BridgeTable =
DISTINCT(
SELECTCOLUMNS(
UNION(
SELECTCOLUMNS(TableA, "CustomerID", TableA[CustomerID], "ProductID", TableA[ProductID]),
SELECTCOLUMNS(TableB, "CustomerID", TableB[CustomerID], "ProductID", TableB[ProductID])
),
"CustomerID", [CustomerID],
"ProductID", [ProductID]
)
)然後在模型中建立:
TableA[CustomerID, ProductID] → BridgeTable[CustomerID, ProductID] ← TableB[CustomerID, ProductID]實際上要拆成兩條一對多的關聯線
若不想用 DAX,可以在「Power Query 編輯器」中操作:
TableA → 「新增欄位」→「自訂欄位」。[CustomerID] & "-" & [ProductID]CompositeKey。TableB 做同樣的事。這方法效能通常比在 DAX 模型層建立計算欄位更好。
NULL 值,記得用 COALESCE() 或 IF 處理。