Qlikview Data Modeling---建立一個Key/Link Table,qlikview
這一篇我們將來學習下在什麼情況下需要在QlikView裡建立一個Key或者Link Table來避免事實表loops 和 qlikview自動產生synthetic keys。當兩個事實表共用同樣的鍵集合的時候,concatenation應該是首選方案去避免qlikview自動的建立synthetic key. 然而,如果一個事實表的比另外一個事實表的key鍵多,而且多出的key鍵值和另外一個事實表沒有關聯,這個時候建立一個key table去串連這些鍵值的方案就更加適合。
Store:
Load * Inline [
StoreID, StoreName
1, Store A
2, Store B
];
Calendar:
Load MonthID As DateID, Month Inline [
MonthID, Month
1, Jan
2, Feb
];
Product:
Load * Inline [
ProductID, Product
1, Product A
2, Product B
];
Sales:
LOAD * INLINE [
DateID, StoreID, ProductID, SaleQty, SaleValue
1, 1, 1, 2, 23
1, 1, 2, 4, 24
2, 1, 1, 4, 33
2, 1, 2, 3, 28
1, 2, 1, 2, 21
1, 2, 2, 4, 30
2, 2, 1, 3, 25
];
Budget:
LOAD * INLINE [
StoreID, ProductID, BudgetQty, BudgetValue
1, 1, 5, 50
1, 2, 6, 47
2, 1, 5, 41
2, 2, 4, 27
];
載入資料後,查看Data Model 如下:
從上面可以看出,QLIKVIEW幫我們自動產生了一個synthetic key named $Syn1 includes ProductID and StoreID. Budget和Sales兩個表同時共用一個$Syn1,但是Sales事實表比Budget事實表多一個key named DateID. 所以這種情況下用concatenate不太適合。
這個時候我們可們可以為Sales和Budget表建立一個鍵欄位 (key filed),它包含兩個表的共同的鍵欄位。如下所示:
第一步:為Sales和Budget表建立一個鍵欄位 (key filed),它包含兩個表的共同的鍵欄位
Sales:
LOAD
AutoNumberHash256(StoreID, ProductID) As SalesBudgetID,
*
INLINE [
DateID, StoreID, ProductID, SaleQty, SaleValue
1, 1, 1, 2, 23
1, 1, 2, 4, 24
2, 1, 1, 4, 33
2, 1, 2, 3, 28
1, 2, 1, 2, 21
1, 2, 2, 4, 30
2, 2, 1, 3, 25
];
Budget:
LOAD
AutoNumberHash256(StoreID, ProductID) As SalesBudgetID,
*
INLINE [
StoreID, ProductID, BudgetQty, BudgetValue
1, 1, 5, 50
1, 2, 6, 47
2, 1, 5, 41
2, 2, 4, 27
];
第二步:通過Sales表的資料建立一個key table
Key:
Load Distinct
SalesBudgetID,
StoreID,
ProductID
Resident
Sales;
第三步: 和Budget表所有匹配的記錄進行串連Join
Join (Key)
Load Distinct
SalesBudgetID,
StoreID,
ProductID
Resident
Budget;
第四步:刪除Sales和Budget表裡的已經在Key Table裡的欄位
// These fields are no longer needed in the fact tables
Drop Fields StoreID, ProductID From Sales;
Drop Fields StoreID, ProductID From Budget;
第五步:Reload the script.此時的Data Model如:
Now that the synthetic key is gone.
Note:
1,這裡的Join Load,是full outer join,他能包含兩個表裡的所有可能的值到key table.所有的在product 或則 store表裡的選擇任然可以正確的關聯到Sales和Budget事實表上。其中的load裡的distinct字句是保證只有唯一的值才被添加到key table裡。
2,AutoNumberHash265是一個可以為相同的資訊組合返回同樣的一個整型值。如果是想把好幾個值轉換成一個整型的值的話,這個函數就可以做到。你需要注意的是該函數只能保證在同一個load script裡返回同樣的值。在不同的load script裡就不能保證了。
3,當然這個例子我們完全可以用concatenate來處理,上面只是在什麼情況下和如何使用key/link table.
4,用concatenate處理如下:
Store:
Load * Inline [
StoreID, StoreName
1, Store A
2, Store B
];
Calendar:
Load MonthID As DateID, Month Inline [
MonthID, Month
1, Jan
2, Feb
];
Product:
Load * Inline [
ProductID, Product
1, Product A
2, Product B
];
Sales:
LOAD
*
INLINE [
DateID, StoreID, ProductID, SaleQty, SaleValue
1, 1, 1, 2, 23
1, 1, 2, 4, 24
2, 1, 1, 4, 33
2, 1, 2, 3, 28
1, 2, 1, 2, 21
1, 2, 2, 4, 30
2, 2, 1, 3, 25
];
//Budget:
Concatenate (Sales)
LOAD
*
INLINE [
StoreID, ProductID, BudgetQty, BudgetValue
1, 1, 5, 50
1, 2, 6, 47
2, 1, 5, 41
2, 2, 4, 27
];
Data Model如:
當然此data model也是沒有synthetic key的。