Function table / Table calculations / Next period revenue

Next period revenue, from Tableau to SQL

Returns the next addressed regional period revenue. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

LOOKUP(SUM([Revenue]), 1)

Compute using: addressing Period; partitioning Region

Sample data

RegionPeriodRevenueCost
Harbor112070
Harbor2180100
Harbor3180120
Harbor4240140
Upland19050
Upland2150110
Upland3null90
Upland4330190

The same calculation as SQL

SELECT CAST((lead("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"

Runs the example above.

Result

RegionPeriodRevenueCostresult
Harbor112070180
Harbor2180100180
Harbor3180120240
Harbor4240140null
Upland19050150
Upland2150110null
Upland3null90330
Upland4330190null

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

Where a naive translation goes wrong

  • An unpartitioned SQL window mixes independent regional calculation sequences.

    Naive SQL

    SELECT CAST((lead("Revenue",1) OVER ( ORDER BY "Period")) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor11207090
    Harbor2180100150
    Harbor3180120null
    Harbor4240140330
    Upland19050180
    Upland2150110180
    Upland3null90240
    Upland4330190null

    Matches the calculation

    SELECT CAST((lead("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor112070180
    Harbor2180100180
    Harbor3180120240
    Harbor4240140null
    Upland19050150
    Upland2150110null
    Upland3null90330
    Upland4330190null

Signature

LOOKUP(SUM([Revenue]), 1)