LOOKUP(SUM([Sales]), 1) reads the next mark's sales. In SQL that is lead(sum(Sales)) OVER (PARTITION BY Region ORDER BY Month). The last month of each region has no next mark and returns null.
Updated · Checked on the xmetric engine
What is the syntax?
LOOKUP(SUM([Sales]), 1)
Returns a number: the expression on the next mark, or null on the last mark of the partition.
What does it return, and what is the SQL?
Each example runs on the same 9 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
How do I show next month's sales beside this month's?
Tableau
LOOKUP(SUM([Sales]), 1)
Compute using Month, restarting for each Region
SQL (DuckDB)
SELECT Region,
Month,
lead(sum(Sales)) OVER (PARTITIONBY Region ORDERBY Month) AS result
FROM input
GROUPBY Region, Month
ORDERBY Region, Month
Compute using Month: East month 1 shows 120, month 4 null. West month 2 shows the null of month 3.
Region
Month
Result
East
1
120
East
2
60
East
3
120
East
4
null
West
1
70
West
2
null
West
3
90
West
4
null
✓ The Tableau formula and the SQL return the same 8 rows.
Where does a straight translation go wrong?
Common mistake
Why does East's last month show West's sales?
Without PARTITION BY, lead runs on into the next region, so East month 4 reads West month 1 (50). Compute Using Month stops at the edge of each region.
Tableau
LOOKUP(SUM([Sales]), 1)
Compute using Month, restarting for each Region
Tempting SQL
SELECT Region,
Month,
lead(sum(Sales)) OVER (ORDERBY Region, Month) AS result
FROM input
GROUPBY Region, Month
ORDERBY Region, Month
SQL that matches
SELECT Region,
Month,
lead(sum(Sales)) OVER (PARTITIONBY Region ORDERBY Month) AS result
FROM input
GROUPBY Region, Month
ORDERBY Region, Month
Region
Month
Tableau
Tempting SQL
SQL that matches
East
1
120
120
120
East
2
60
60
60
East
3
120
120
120
East
4
null
50
null
West
1
70
70
70
West
2
null
null
null
West
3
90
90
90
West
4
null
null
null
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
How do I write it in Snowflake or BigQuery?
The first example, written for each warehouse from its documentation. These are not run here; DuckDB is.
Snowflake
SELECT Region,
Month,
LEAD(SUM(Sales)) OVER (PARTITIONBY Region ORDERBY Month) AS result
FROM input
GROUPBY Region, Month
ORDERBY Region, Month
A table calculation runs on the marks in the view, so its argument must be an aggregate. A bare field such as [Sales] raises an error; see All fields must be aggregate or constant.
Is it lead or lag?
A positive LOOKUP offset looks forward, which is lead; a negative one looks back, which is lag.
How do I read two months ahead?
LOOKUP(SUM([Sales]), 2), in SQL lead(sum(Sales), 2) with the same window.