[d] - [b] moves a date-time back by b days and keeps its time of day. In DuckDB, subtract an interval: d - to_days(b). Casting to DATE first, so that plain integer subtraction works, throws the time away.
Updated · Checked on the xmetric engine
What is the syntax?
date - number
date
a date or date-time.
number
days to subtract.
Returns a date or date-time number days earlier. Null if either side is null.
What does it return, and what is the SQL?
Each example runs on the same 8 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
What is the date b days before d?
Tableau
[d]-[b]
SQL (DuckDB)
SELECT d -to_days(b) AS result
FROM input
ORDERBY id
Row 1: 28 February 18:00 minus 2 days is 26 February 18:00.
b
d
Result
2
2024-02-2818:00
2024-02-2618:00
2
2024-02-2900:00
2024-02-2700:00
5
2024-03-0109:30
2024-02-2509:30
4
2025-01-0112:00
2024-12-2812:00
3
null
2
2024-01-0108:00
2023-12-3008:00
2024-12-3123:00
null
−2
2024-06-1510:00
2024-06-1710:00
✓ The Tableau formula and the SQL return the same 8 rows.
Where does a straight translation go wrong?
Common mistake
Why does casting to DATE lose the time?
DuckDB lets you subtract an integer from a DATE, but the cast drops the time of day. Tableau keeps it: 18:00 stays 18:00.
Tableau
[d]-[b]
Tempting SQL
SELECTCAST (d AS DATE) -CAST (b AS INTEGER) AS result
FROM input
ORDERBY id
SQL that matches
SELECT d -to_days(b) AS result
FROM input
ORDERBY id
b
d
Tableau
Tempting SQL
SQL that matches
2
2024-02-2818:00
2024-02-2618:00
2024-02-26
2024-02-2618:00
2
2024-02-2900:00
2024-02-2700:00
2024-02-27
2024-02-2700:00
5
2024-03-0109:30
2024-02-2509:30
2024-02-25
2024-02-2509:30
4
2025-01-0112:00
2024-12-2812:00
2024-12-28
2024-12-2812:00
3
null
null
null
2
2024-01-0108:00
2023-12-3008:00
2023-12-30
2023-12-3008:00
2024-12-3123:00
null
null
null
−2
2024-06-1510:00
2024-06-1710:00
2024-06-17
2024-06-1710:00
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
How do I go back one day?
Subtract a constant; in SQL, a literal interval. Columns 1 to 8 are the sample rows, by id.
Case
Tableau, then SQL (DuckDB)
1
2
3
4
5
6
7
8
minus 1 day
[d] - 1d - INTERVAL 1 DAY
2024-02-2718:00
2024-02-2800:00
2024-02-2909:30
2024-12-3112:00
null
2023-12-3108:00
2024-12-3023:00
2024-06-1410:00
✓ On every row, each Tableau formula and its SQL return the same value.
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
SELECTDATEADD(day, - b, d) AS result
FROM input
ORDERBY id