多个Max ID的SQL插入查询

多个Max ID的SQL插入查询,sql,sql-server,sql-insert,insert-update,insert-into,Sql,Sql Server,Sql Insert,Insert Update,Insert Into,表w: |ID|Comment|SeqID| |1 |bajg | 1 | |1 |2423 | 2 | |2 |ref | 1 | |2 |comment| 2 | |2 |juk | 3 | |3 |efef | 1 | |4 | hy | 1 | |4 | 6u | 2 | |2 |juk | 3 | 如何为新的SeqID(SeqID增加1)的每个ID插入标准的新注释 以下查询结果为最高的SeqID: Sel

表w:

|ID|Comment|SeqID|
|1 |bajg   | 1   |
|1 |2423   | 2   |
|2 |ref    | 1   |
|2 |comment| 2   |
|2 |juk    | 3   |
|3 |efef   | 1   |
|4 | hy    | 1   |
|4 | 6u    | 2   |
|2 |juk    | 3   |
如何为新的SeqID(SeqID增加1)的每个ID插入标准的新注释

以下查询结果为最高的SeqID:

Select *
From w
Where SEQID = 
(select max(seqid)
from w)
表w:

|ID|Comment|SeqID|
|1 |bajg   | 1   |
|1 |2423   | 2   |
|2 |ref    | 1   |
|2 |comment| 2   |
|2 |juk    | 3   |
|3 |efef   | 1   |
|4 | hy    | 1   |
|4 | 6u    | 2   |
|2 |juk    | 3   |
预期结果 表w:

我是否必须使用下面的命令将所有我想要的值(新注释为sqc)插入到表中,还是有更快的方法

INSERT INTO table_name
 VALUES (value1,value2,value3,...);
试试这个:

INSERT INTO mytable (ID, Comment, SeqID)
SELECT ID, 'sqc', MAX(SeqID) + 1
FROM mytable
GROUP BY ID

您最好在查询时只计算值。在表上定义一个
identity
列,比如说
CommentId
,然后运行如下查询:

select id, comment,
       row_number() over (partition by comment order by CommentId) as SeqId
from t;

这种方法的好处在于,ID始终是连续的,没有重复的机会,插入时不必锁定表,连续ID甚至可以用于更新和删除。

sqc来自哪里?我有点不清楚你到底想做什么?更新现有记录或生成新记录?sqc是我要添加的新注释。该表包含所有注释,每个新添加的注释都是按顺序添加的。例如:如果我为ID 1添加一个新注释“hihi”(查看表w中的数据),它将在数据库| 1 | hihi | 3 |中添加一个新行。所以要创造一个新的记录