透過 DRY LookML 盡量提高程式碼重複使用性:為複雜計算定義可重複使用的指標

在 LookML 中定義複雜的計算時,將這些計算分解為涉及較簡單計算的中間步驟,可能會很有幫助。建立中間指標可讓計算結果更易讀、更易維護,且不易出錯,因為您只需要確保每個中間計算結果都正確無誤。

本頁面提供範例,說明如何定義中間指標,將複雜的計算作業分解為更容易管理的步驟,讓 LookML 中的計算作業更易於閱讀及維護。

食材

事前準備

範例:將複雜的計算分解為中間測量指標

假設您是一家線上產品銷售公司的負責人,想要定義用來計算總利潤和股東股利的評估指標。其中一種方法是定義兩個指標:total_profit 指標和 shareholder_dividends 指標,如下所示:


measure: total_profit {
  type: number
  sql: SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost}) ;;
}

measure: shareholder_dividends
  description: "We give shareholders 60% of our total profits."
  type: number
  sql: 0.6 * (SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost})) ;;

在這個範例中,計算 SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost}) 會重複使用兩個指標的 sql 參數。如果您需要更新這項計算的定義 (例如修正錯誤),就必須為這兩項指標手動更新計算。

您可以重複使用 shareholder_dividends 指標中的計算值,在 total_profit 指標中重新定義這些指標,以便更輕鬆地維護這些指標定義:


measure: total_profit {
  type: number
  sql: SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost}) ;;
}

measure: shareholder_dividends
  description: "We give shareholders 60% of our total profits."
  type: number
  sql: 0.6 * ${total_profit} ;;

您可能會將 total_profit 中的計算分解為更簡單的指標,以便在其他計算中重複使用。舉例來說,您可以建立名為 total_salestotal_revenuetotal_costtotal_salarytype: sum 措施:


measure: total_sales {
  hidden: yes
  type: sum
  sql: ${orders.sale_price} ;;
}

measure: total_revenue {
  hidden: yes
  type: number
  sql: ${total_sales} ;;
}

measure: total_cost {
  hidden: yes
  type: sum
  sql: ${products.cost} ;;
}

measure: total_salary {
  hidden: yes
  type: sum
  sql: ${employees.salary} ;;
}

接著,您可以重複使用已定義的中介欄位,如下所示:


measure: total_expenses {
  type: number
  sql: ${total_cost} + ${total_salary} ;;
}

measure: total_profit {
  type: number
  sql: ${total_revenue} - ${total_expenses} ;;
}

measure: shareholder_dividends {
  description: "We give shareholders 60% of our total profits."
  type: number
  sql: 0.6 * ${total_profit} ;;
}

雖然您已定義更多指標,但這些中間指標可在其他計算中重複使用,因此更容易修正錯誤,或對多個指標中使用的計算進行任何變更。