sql_distinct_key

用量

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 的基本衡量指标,您会得到 80.00 的总和,即使实际收取的总运费为 30.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,依此类推。