HEXBINX: from Tableau to SQL

Returns the horizontal coordinate of the nearest hexagonal bin center. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

HEXBINX([amount], [other])

Sample data

idamountunitsscoreother
1-2.52-0.83
20004
31.530.252
4440.58
5950.811
6166114
7null7null9
848-0.5null

The same calculation as SQL

WITH coords AS (SELECT *,coalesce(amount,0) AS x,coalesce(other,0)/sqrt(3) AS y FROM input), centers AS (SELECT *,3*floor(x/3+0.5) AS ux,floor(y+0.5) AS uy,3*floor((x-1.5)/3+0.5)+1.5 AS sx,floor(y) +0.5 AS sy FROM coords) SELECT CASE WHEN amount IS NULL THEN NULL WHEN pow(ux-x,2)+3*pow(uy-y,2)<=pow(sx-x,2)+3*pow(sy-y,2) THEN ux ELSE sx END AS result FROM centers ORDER BY id

Runs the example above.

Result

idamountunitsscoreresult
1-2.52-0.8-3
20000
31.530.251.5
4440.54.5
5950.89
6166116.5
7null7nullnull
848-0.53

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

Where a naive translation goes wrong

  • Rounding an axis independently does not select the nearest hexagonal center.

    Naive SQL

    SELECT round(amount) AS result FROM input ORDER BY id
    idamountunitsscoreresult
    1-2.52-0.8-3
    20000
    31.530.252
    4440.54
    5950.89
    6166116
    7null7nullnull
    848-0.54

    Matches the calculation

    WITH coords AS (SELECT *,coalesce(amount,0) AS x,coalesce(other,0)/sqrt(3) AS y FROM input), centers AS (SELECT *,3*floor(x/3+0.5) AS ux,floor(y+0.5) AS uy,3*floor((x-1.5)/3+0.5)+1.5 AS sx,floor(y) +0.5 AS sy FROM coords) SELECT CASE WHEN amount IS NULL THEN NULL WHEN pow(ux-x,2)+3*pow(uy-y,2)<=pow(sx-x,2)+3*pow(sy-y,2) THEN ux ELSE sx END AS result FROM centers ORDER BY id
    idamountunitsscoreresult
    1-2.52-0.8-3
    20000
    31.530.251.5
    4440.54.5
    5950.89
    6166116.5
    7null7nullnull
    848-0.53

Signature

HEXBINX(number, number)