From Postgres I am used to do:
with a as (
with b as (
SELECT
...
)
SELECT
...
),
c as (
SELECT
...
)
SELECT
...
This type of nesting (or CTE hierarchy) of a & b does not execute in T-SQL however.
Is there a workaround for this, a simple rewrite as suggested in Can you create nested WITH clauses for Common Table Expressions? like
with a as (
SELECT
...
),
b as (
SELECT
...
),
c as (
SELECT
...
)
SELECT
...
is not possible in my case (see query below), as in many other cases.
Would be glad for some pointers since I am new to T-SQL.
--generate a time-series in 15min intervals, ending with the last incoming user
WITH last_timeslot AS (
--get the last ts from one of the two tables with less recent entries
SELECT
dateadd(
MINUTE,
datediff(
MINUTE,
0,
LEAST(
(SELECT
MAX(ts)
FROM dbo.user u )
,
(SELECT
MAX(ts)
FROM dbo.user_history uh )
)
)/ 15 * 15, --round to 15min slot
0
) AS last_timeslot_ts
),
timeslot_series AS (
--recursively generate a timeseries going back 14 days from the last timeslot, in 15min steps
WITH cte AS (
SELECT DATEADD(DAY,-14,(SELECT last_timeslot_ts FROM last_timeslot)) AS slot
UNION ALL
SELECT DATEADD(MINUTE,15,slot)
FROM cte
WHERE DATEADD(MINUTE,15,slot) < (SELECT last_timeslot_ts FROM last_timeslot)
)
SELECT slot
FROM cte
OPTION (MAXRECURSION 0)
),
c as (
--other stuff happens
SELECT
...
FROM timeslot_series
LEFT JOIN
...
)
SELECT ...