简体   繁体   中英

Expand table with key column to full table with null values - SQL Server select query

I have a clean table, and I want to expand it so that in rows without values I get NULL with a SQL select query.

For example this is table A:

key text
1 t1
2 t2
5 t3
7 t4

I'm trying to get this output:

key text
1 t1
2 t2
3 null
4 null
5 t3
6 null
7 t4

Any help?

You need to generate the additional rows. One method uses recursive subqueries:

with cte as (
      select min(key) as key, max(key) as max_key
      from a
      union all
      select key + 1, max_key
      from cte
      where key < max_key
     )
select cte.key, a.key
from cte left join
     a
     on a.key = cte.key
option (maxrecursion 0);

Note that recursive CTEs are not necessarily the fastest method to do this, but they are the Standard SQL approach to the problem and the performance is fine up to thousands of rows.

If you have a numbers or calendar table on hand, then that is another easy way to get all the values you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM