Search code examples
sqlsql-servert-sqlsql-server-2008-r2sql-server-2014-express

How to split table into two tables based on column value in sql?


I need to split a table into two tables based on a value of column by creating two tables in data-base for example:

I have a table as the below

table1

|---------------------|------------------|
|        Col1         |     Col2         |
|---------------------|------------------|
|         1           |         a        |
|---------------------|------------------|
|         2           |         a        |
|---------------------|------------------|
|         3           |         b        |
|---------------------|------------------|
|         4           |         a        |
|---------------------|------------------|
|         5           |         b        |
|---------------------|------------------|
|         6           |         b        |
|---------------------|------------------|
|         7           |         a        |
|---------------------|------------------|

and the result I want to be like this as the below tables

table2

|---------------------|------------------|
|        Col1         |     Col2         |
|---------------------|------------------|
|         1           |         a        |
|---------------------|------------------|
|         2           |         a        |
|---------------------|------------------|
|         4           |         a        |
|---------------------|------------------|
|         7           |         a        |
|---------------------|------------------|

table3

|---------------------|------------------|
|        Col1         |     Col2         |
|---------------------|------------------|
|         3           |         b        |
|---------------------|------------------|
|         5           |         b        |
|---------------------|------------------|
|         6           |         b        |
|---------------------|------------------|

Solution

  • You can use a SELECT...INTO statement:

    create table #table1 (col1 int, col2 char(1))
    
    insert into #table1 
    values
     (1,'a')
    ,(2,'a')
    ,(3,'b')
    ,(4,'a')
    ,(5,'b')
    ,(6,'b')
    ,(7,'a')
    
    select Col1, Col2 into #table2
    from #table1
    where Col2 = 'a'
    
    select Col1, Col2 into #table3
    from #table1
    where Col2 = 'b'
    

    Here are the resulting #table2 and #table3:

    enter image description here