Home > Software engineering >  Generate a series between 2 column values in SQL
Generate a series between 2 column values in SQL

Time:10-21

I have a table with the following structure:

FromAccount ToAccount Team Location
100 150 a 5
151 300 b 4
301 322 c 4

I would like to run an SQL query on the table that would return a 1 series for the FromAccount to ThruAccount with the Team and Location columns that belong to that series. I think this table would look something like this where a record is returned for each 1 value in the From Thru Span.

Account Team Location
100 a 5
102 a 5
103 a 5
... ... ...
... ... ...
149 a 5
150 a 5
151 b 4
152 b 4
... ... ...
300 c 4
... ... ...
321 c 4
322 c 4

Can this be done in SQL Server?

CodePudding user response:

Assuming 101 was just missing due to a typo, we can use a recursive CTE to generate all the numbers between the lowest from and the highest to, then join to them.

DECLARE @min int, @max int;

SELECT @min = MIN(FromAccount), @max = MAX(ToAccount)
  FROM dbo.TableName;

WITH n(n) AS (SELECT @min UNION ALL
  SELECT n 1 FROM n WHERE n < @max
)
SELECT Account = n.n,
  t.Team, t.Location
FROM dbo.TableName AS t
INNER JOIN n
ON n.n BETWEEN t.FromAccount AND t.ToAccount
OPTION (MAXRECURSION 0);
  • Related