简体   繁体   中英

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

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 :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM