用量
view: view_name {
measure: field_name {
type: sum_distinct
sql_distinct_key: ${my_field_name} ;;
}
}
|
階層
sql_distinct_key |
可能的欄位類型
評估
接受
SQL 運算式
|
定義
sql_distinct_key 參數會與對非重複值執行匯總作業的指標類型搭配使用,特別是 average_distinct、median_distinct、percentile_distinct 和 sum_distinct 類型的指標。sql_distinct_key 會告知 Looker 要使用哪個欄位做為判斷不重複值的依據,藉此避免在扇出時發生誤算。
舉例來說,type: sum_distinct 會根據 sql_distinct_key 參數定義的唯一值,加總指定欄位中的非重複值。
請參考下表:
| 訂單項目 ID | 訂單 ID | 訂單出貨 |
|---|---|---|
| 1 | 1 | 10.00 |
| 2 | 1 | 10.00 |
| 3 | 2 | 20.00 |
| 4 | 2 | 20.00 |
| 5 | 2 | 20.00 |
在這種情況下,每筆訂單都會有多個資料列。如果您在「order_shipping」欄中新增基本指標 type: sum,即使實際收取的運費總額為 30.00,系統仍會顯示總額 80.00。
# Will NOT calculate the correct shipping amount
measure: total_shipping {
type: sum
sql: ${order_shipping} ;;
}
如要取得準確結果,請使用 sql_distinct_key 參數向 Looker 說明如何識別每個不重複的實體 (在本例中為每筆不重複的訂單)。這會計算出正確的 30.00 金額:
# Will calculate the correct shipping amount
measure: total_shipping {
type: sum_distinct
sql_distinct_key: ${order_id} ;;
sql: ${order_shipping} ;;
}
sql_distinct_key 的每個不重複值在 sql 中都只能有一個對應值。這個範例之所以有效,是因為 每個 order_id 為 1 的資料列都有相同的 order_shipping 值 10.00,每個 order_id 為 2 的資料列都有相同的 order_shipping 值 20.00,依此類推。