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_distinctmedian_distinctpercentile_distinctsum_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,依此类推。