Assuming you named your Data table, below you will get the results you published.
- The
WITH statement creates a temporary memory table containing all rows from 1 to the maximum that are present in your actual table. CROSS APPLY returns a row for each bar existing in your table or not.- the
CASE statement selects an existing baz if present, 0 if not.
SQL statement
WITH q AS ( SELECT [bar] = 1 , [MaxBar] = MAX(bar) FROM Data UNION ALL SELECT q.bar + 1 , q.MaxBar FROM q WHERE q.bar + 1 <= q.MaxBar ) SELECT Data.foo , q.bar , CASE WHEN q.bar = Data.bar THEN Data.baz ELSE 0 END FROM q CROSS APPLY Data ORDER BY Data.foo , q.bar
Test script
WITH Data AS ( SELECT [foo] = 1, [bar] = 1, [baz] = 2 UNION ALL SELECT 2, 3, 4 ), q AS ( SELECT [bar] = MIN(bar) , [MaxBar] = MAX(bar) FROM Data UNION ALL SELECT q.bar + 1 , q.MaxBar FROM q WHERE q.bar + 1 <= q.MaxBar ) SELECT Data.foo , q.bar , CASE WHEN q.bar = Data.bar THEN Data.baz ELSE 0 END FROM q CROSS APPLY Data ORDER BY Data.foo , q.bar
source share