ATTR: from Tableau to SQL

Returns the sole distinct non-null value, or a multiple-value marker. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

ATTR([amount])

Sample data

idamountunitsscoreother
142-0.83
24004
3430.252
4440.58
5450.811
646114
7null7null9
848-0.5null

The same calculation as SQL

SELECT CASE WHEN count(DISTINCT amount)=0 THEN NULL WHEN count(DISTINCT amount)=1 THEN min(amount) ELSE NULL END AS result FROM input

Runs the example above.

Result

result
4

Same rows from the calculation and from the SQL in DuckDB.

Where a naive translation goes wrong

  • MIN silently selects a value when ATTR detects multiple distinct values.

    Naive SQL

    SELECT min(amount) AS result FROM input
    result
    -2.5

    Matches the calculation

    SELECT CASE WHEN count(DISTINCT amount)=0 THEN NULL WHEN count(DISTINCT amount)=1 THEN cast(min(amount) AS VARCHAR) ELSE '*' END AS result FROM input
    result
    *

Signature

ATTR(expression)