<br />

## Usage

```
view: view_name {
  measure: field_name {
    type: sum_distinct
    sql_distinct_key: ${my_field_name} ;;
  }
}
```

|---|---|
| Hierarchy [View File](https://docs.cloud.google.com/looker/docs/reference/param-view.md.txt) [`view`](https://docs.cloud.google.com/looker/docs/reference/param-view-view.md.txt) [measure](https://docs.cloud.google.com/looker/docs/reference/param-field-measure.md.txt) `sql_distinct_key` | Possible Field Types Measure <br /> Accepts A SQL expression <br /> |

## Definition

The `sql_distinct_key` parameter is used with measure types that perform aggregations on non-repeated values, specifically measures of type [`average_distinct`](https://docs.cloud.google.com/looker/docs/reference/param-measure-types.md.txt#average_distinct), [`median_distinct`](https://docs.cloud.google.com/looker/docs/reference/param-measure-types.md.txt#median_distinct), [`percentile_distinct`](https://docs.cloud.google.com/looker/docs/reference/param-measure-types.md.txt#percentile_distinct), and [`sum_distinct`](https://docs.cloud.google.com/looker/docs/reference/param-measure-types.md.txt#sum_distinct). `sql_distinct_key` tells Looker which field to use as a basis for determining unique values, thereby avoiding miscalculations in the case of a [fanout](https://discuss.google.dev/t/the-problem-of-sql-fanouts/119220).

For example, `type: sum_distinct` adds up the nonrepeated values in a given field, based on the unique values defined by the [`sql_distinct_key`](https://docs.cloud.google.com/looker/docs/reference/param-field-sql-distinct-key.md.txt) parameter.

Consider a table like this:

| Order Item ID | Order ID | Order Shipping |
|---|---|---|
| 1 | 1 | 10.00 |
| 2 | 1 | 10.00 |
| 3 | 2 | 20.00 |
| 4 | 2 | 20.00 |
| 5 | 2 | 20.00 |

In this situation, there are multiple rows for each order. If you added a basic measure of `type: sum` for the `order_shipping` column, you get a total of 80.00, even though the total shipping collected is actually 30.00.

     # Will NOT calculate the correct shipping amount
    measure: total_shipping {
      type: sum
      sql: ${order_shipping} ;;
    }

To get an accurate result, you can explain to Looker how it should identify each unique entity (in this case, each unique order) by using the `sql_distinct_key` parameter. This *will* calculate the correct 30.00 amount:

     # Will calculate the correct shipping amount
    measure: total_shipping {
      type: sum_distinct
      sql_distinct_key: ${order_id} ;;
      sql: ${order_shipping} ;;
    }

Every unique value of `sql_distinct_key` must have just one corresponding value in [`sql`](https://docs.cloud.google.com/looker/docs/reference/param-field-sql.md.txt). This example works because *every* row with an `order_id` of 1 has the same `order_shipping` of 10.00, *every* row with an `order_id` of 2 has the same `order_shipping` of 20.00, etc.