How to use "Select count()" query in an insert statement?

  • Hi,

    I would like to know the following:

    1. Assume my new table "Table1" has 2 columns

    2. For the 1st column, I require to insert values based on another table "Table2" using the below condition.

    If the count of a field ("Field1") in Table2 is greater than 1 --> insert "All" in Table1

    Else, insert "Group" in Table1

    I tried using the following query:

    INSERT INTO Table1 (Column1, Column2) VALUES

    (CASE WHEN c.cnt > 1 THEN 'ALL'

    ELSE 'GROUP'

    END, c.Column2

    (SELECT COUNT(Column1) as cnt, Column2 from Table2

    Group by Column2) as c)

    Can you please help me in this query?

    Thanks and Regards,

    Geeth

  • Since the rows you're inserting are based on the other table, lose the "VALUES()" portion of the query. The INSERT/SELECT method is what you need, and you seem to be trying to combine both types.

  • insert x

    select case when count(a) > 1 then 'All' else 'group' end 'firstcol'

    , secondcol

    ...

    from table

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply