SELECT INTO查询

时间:2014-07-29 21:59:07

标签: sql-server tsql

我必须为包含SELECT INTO T-SQLacc_numberhistory_number列的表编写note脚本。

如何为通过history_number

插入的每条记录提供SELECT INTO.的增量值

请注意,history_number的值会从不同的表格中显示为每个account的不同值。

3 个答案:

答案 0 :(得分:0)

SELECT history_number = IDENTITY(INT,1,1),
    ... etc...
INTO NewTable
FROM ExistingTable
WHERE ...

您可以使用ROW_NUMBER代替身份,即ROW_NUMBER()OVER(ORDER BY)

答案 1 :(得分:0)

SELECT acc_number
    ,o.historynumber
    ,note
    ,o.historynumber+DENSE_RANK() OVER (Partition By acc_number ORDER BY Note) AS NewHistoryNumber 
                                                              --Or some other order by probably a timestamp...
FROM Table t
INNER JOIN OtherTable o
ON ....

Working Fiddle

将从每个accnum的历史记录编号开始递增计数。我建议你在排名中使用更好的顺序,但问题中没有足够的信息。

这个问题的答案也可能对你有所帮助 Question

答案 2 :(得分:0)

假设您的SELECT语句是这样的

SELECT  acc_number,
        history_number,
        note
FROM    [Table]

尝试以下查询。

SELECT  ROW_NUMBER() OVER (ORDER BY acc_number) ID,
        acc_number,
        history_number,
        note    
INTO    [NewTable]
FROM    [Table]
相关问题