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