繁体   English   中英

如何基于具有相同元素的列将SQL表拆分为多个?

[英]How can I split a SQL table into multiple based on columns which have the same elements?

目前,我有一个大的SQL表。 假设它看起来像这样:

Table: allData
County Census Tract Population Name
001    xxxxxx       4328       County1
001    yyyyyy       4729       County1
002    zzzzzz       5629       County2
003    aaaaaa       3947       County3

我想要的是每个县的单独表格。 所以我会有:

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

谢谢。

如果您的用例需要为每个县使用单独的表,则可以使用以下SQL生成create table语句

select 'create table '+Name+' as select * from allData where name = '''+Name+''';'
  from allData
 group by name

该SQL将生成insert语句

select 'insert into '+Name+' select * from allData where name = '''+Name+''';'
  from allData
 group by name

您可以运行上述每种方法,然后将结果复制粘贴到SQL客户端中,以创建并填充表

如果您需要指定架构名称,则将其添加在“ Name之前,例如

select 'create table <schema.>'+Name+' as select * from allData where name = '''+Name+''';'

我已经使用以下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.

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