FIRST: from Tableau to SQL

Returns the relative offset to the first mark in the partition. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

FIRST()

Compute using: addressing Period; partitioning Region

Sample data

RegionPeriodRevenueCost
Harbor112070
Harbor2180100
Harbor3180120
Harbor4240140
Upland19050
Upland2150110
Upland3null90
Upland4330190

The same calculation as SQL

SELECT CAST((1-row_number() OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"

Runs the example above.

Result

RegionPeriodRevenueCostresult
Harbor1120700
Harbor2180100-1
Harbor3180120-2
Harbor4240140-3
Upland190500
Upland2150110-1
Upland3null90-2
Upland4330190-3

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

Where a naive translation goes wrong

  • Omitting the region partition allows a calculation to consume marks from other regions.

    Naive SQL

    SELECT CAST((1-row_number() OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700
    Harbor2180100-2
    Harbor3180120-4
    Harbor4240140-6
    Upland19050-1
    Upland2150110-3
    Upland3null90-5
    Upland4330190-7

    Matches the calculation

    SELECT CAST((1-row_number() OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700
    Harbor2180100-1
    Harbor3180120-2
    Harbor4240140-3
    Upland190500
    Upland2150110-1
    Upland3null90-2
    Upland4330190-3

Signature

FIRST()