Search code examples
sqlsql-serversql-insertinsert-updateinsert-into

SQL Insert Query For Multiple Max IDs


Table 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   |

How do I insert a standard new comment for each ID for a new SeqID (SeqID increase by 1)

The Below query results in the highest SeqID:

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

Table w:

|2 |juk    | 3   |

Expected Result Table w:

|ID|Comment|SeqID|
|1 |sqc    | 3   |
|2 |sqc    | 4   |
|3 |sqc    | 2   |
|4 |sqc    | 3   |

Will I have to go through and insert all the values (new comment as sqc) I want into the table using the below, or is there a faster way?

INSERT INTO table_name
 VALUES (value1,value2,value3,...);

Solution

  • Try this:

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

    Demo here