[英]How can I split a SQL table into multiple based on columns which have the same elements?
At the moment I have one large SQL table. 目前,我有一个大的SQL表。 Let's say it looks like this: 假设它看起来像这样:
Table: allData
County Census Tract Population Name
001 xxxxxx 4328 County1
001 yyyyyy 4729 County1
002 zzzzzz 5629 County2
003 aaaaaa 3947 County3
What I want is an individual table for each county. 我想要的是每个县的单独表格。 So I would have: 所以我会有:
Table: County1
County Census Tract Population Name
001 xxxxxx 4328 County1
001 yyyyyy 4729 County1
Table: County2
County Census Tract Population Name
002 zzzzzz 5629 County2
Table: County3
County Census Tract Population Name
003 aaaaaa 3947 County3
Thanks. 谢谢。
If your use case requires a separate table for each County you can use the following SQL to generate create table
statements 如果您的用例需要为每个县使用单独的表,则可以使用以下SQL生成create table
语句
select 'create table '+Name+' as select * from allData where name = '''+Name+''';'
from allData
group by name
This SQL will generate insert
statements 该SQL将生成insert
语句
select 'insert into '+Name+' select * from allData where name = '''+Name+''';'
from allData
group by name
You can run each of these above and copy paste the result into your SQL client to create and populate the tables 您可以运行上述每种方法,然后将结果复制粘贴到SQL客户端中,以创建并填充表
If you need to specify schema names add it right before Name
like 如果您需要指定架构名称,则将其添加在“ Name
之前,例如
select 'create table <schema.>'+Name+' as select * from allData where name = '''+Name+''';'
I have used the following SQL to test the same 我已经使用以下SQL测试相同
with allData as (
select '001' County, 'xxxxxx' Census_Tract, 4328 Population, 'County1' Name union all
select '001', 'yyyyyy', 4729, 'County1' union all
select '002', 'zzzzzz', 5629, 'County2' union all
select '003', 'aaaaaa', 3947, 'County3' )
select 'create table '+Name+' as select * from allData where name = '''+Name+''';'
group by name;
with allData as (
select '001' County, 'xxxxxx' Census_Tract, 4328 Population, 'County1' Name union all
select '001', 'yyyyyy', 4729, 'County1' union all
select '002', 'zzzzzz', 5629, 'County2' union all
select '003', 'aaaaaa', 3947, 'County3' )
select 'insert into '+Name+' select * from allData where name = '''+Name+''';'
from allData
group by name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.