简体   繁体   English

将带有键列的表扩展到带有 null 值的完整表 - SQL 服务器 select 查询

[英]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.我有一个干净的表,我想扩展它,以便在没有值的行中我得到 NULL 和 SQL select查询。

For example this is table A:例如这是表 A:

key钥匙 text文本
1 1 t1 t1
2 2 t2 t2
5 5 t3 t3
7 7 t4 t4

I'm trying to get this output:我正在尝试获取此 output:

key钥匙 text文本
1 1 t1 t1
2 2 t2 t2
3 3 null null
4 4 null null
5 5 t3 t3
6 6 null null
7 7 t4 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.请注意,递归 CTE 不一定是最快的方法,但它们是解决问题的标准 SQL 方法,性能可以达到数千行。

If you have a numbers or calendar table on hand, then that is another easy way to get all the values you need.如果您手头有数字或日历表,那么这是获得所需所有值的另一种简单方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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