Home  >  Q&A  >  body text

How to insert records extracted from another table into one table

I'm trying to write a query that extracts and transforms data from a table and then inserts that data into another table. Yes, this is a data warehouse query and I executed it in MS Access. So basically I want some query like this:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
  (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);

I tried it but got a syntax error message.

If you wanted to do this, what would you do?

P粉449281068P粉449281068362 days ago666

reply all(2)I'll reply

  • P粉949267121

    P粉9492671212023-10-11 14:11:14

    You have two syntax options:

    Option 1

    CREATE TABLE Table1 (
        id int identity(1, 1) not null,
        LongIntColumn1 int,
        CurrencyColumn money
    )
    
    CREATE TABLE Table2 (
        id int identity(1, 1) not null,
        LongIntColumn2 int,
        CurrencyColumn2 money
    )
    
    INSERT INTO Table1 VALUES(12, 12.00)
    INSERT INTO Table1 VALUES(11, 13.00)
    
    INSERT INTO Table2
    SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1

    Option 2

    CREATE TABLE Table1 (
        id int identity(1, 1) not null,
        LongIntColumn1 int,
        CurrencyColumn money
    )
    
    INSERT INTO Table1 VALUES(12, 12.00)
    INSERT INTO Table1 VALUES(11, 13.00)
    
    
    SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
    INTO Table2
    FROM Table1
    GROUP BY LongIntColumn1

    Remember that option 2 will create a table containing only the columns on the projection (the columns on the SELECT).

    reply
    0
  • P粉322106755

    P粉3221067552023-10-11 10:09:04

    No "VALUES", no brackets:

    INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
    SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;

    reply
    0
  • Cancelreply