【发布时间】:2020-05-05 21:41:30
【问题描述】:
我正在使用 T-SQL。
我有一个临时表 #t2,其中只有一个名为 internal 的列。
列的值是 n 乘以从 1 到 3 的序列
即: 1 2 3 1 2 3 1 2 3 ...
我想将此列添加到另一个临时表#t1,它只有一个名为Date 的日期列(假设两个表的行数相同)。
如果我想使用连接,我需要一个on 子句,但我没有任何有意义的键。此外,cross join 不起作用,因为它增加了列数。因此,我想在每个表中添加一个row_number,并在新形成的 row_number 列上进行内部连接。
但是,row_number 需要一个 order by 子句,而 #t1 包含列 Date 对排序有意义,而表 #t2 不需要,因此 row_number 解决方案也不起作用。
我尝试将id 列添加到表#t2 并使用while 循环添加row_number,但id 列仅由NULL 值填充。
ALTER TABLE #t2
ADD id integer;
declare @iterFlag integer
declare @iteration2 integer
set @iteration2 = (select count(internal) from #t2)
--print @iteration2
set @intFlag = 1
while (@intFlag <= @iteration2)
begin
INSERT INTO #t2 (id)
VALUES (@intFlag)
SET @intFlag = @intFlag + 1
end;
go
如果不使用
INSERT INTO #t2 (id)
VALUES (@intFlag)
我使用:
UPDATE #t2
SET id = @intFlag
那么我只得到(select count(internal) from #t2)的结果。
您有什么解决方案可以让我将两列并排堆叠吗?
【问题讨论】:
-
请包括表格 DDL、样本数据和所需结果。
-
您可以按常量/空值排序:ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
标签: sql sql-server tsql date window-functions