我的父子表如下所示:
ID, ParentID, Name, Population
1, Null, Asia, 40
2, Null, Africa, 20
3, 1, China, 10
4, 3, Tibet, 5(大约1000行,树的级别可能会有所不同。用户将继续输入新行)
我想要实现一个如下所示的csv文件:
Level1, Level2, Level3, Population
Asia, Null, Null, 40
Africa, Null, Null, 20
Asia, China, Null, 10
Asia, China, Tibet, 5如何从父子表中创建这样的csv文件?第一个挑战是找到父子表的最大层数,然后创建csv报头。第二个挑战是将空值放入没有值的级别。
请注意,用户将不断输入新行...不确定是否应该加载xml格式的父子表,然后开始读取xml文件...请给我一些建议。谢谢
发布于 2011-10-09 06:02:16
看起来您想要从表中构造一个tree,然后对树执行traversal以构造csv文件。树节点将包含两个值: country name和population。
在构建树时,您可能想要记下最大叶节点深度。这将为您提供csv中标题行中的元素数量。然后在遍历过程中,你会想要从根开始跟踪节点的路径,这将是你在csv中打印的内容,该路径中的节点数可以从最大深度中减去,得到给定行中的空值数。
您的Node类将如下所示:
class Node
{
string name;
int population;
Node parent;
List<Node> children;
public Node(Node parent, string name, int population)
{
this.parent = parent;
this.name = name;
this.population = population;
children = new List<Node>();
}
public void Add(Node child)
{
children.Add(child);
}
}发布于 2011-10-09 06:34:49
create table #Populations (ID int PRIMARY KEY, ParentId int null, Name varchar(20), Population int )
insert into #Populations values(1, null, 'Asia', 40)
insert into #Populations values(2, Null, 'Africa', 20)
insert into #Populations values(3, 1, 'China', 20)
insert into #Populations values(4, 3, 'Tibet', 10)
;with FirstLevel(ID, ParentId, Name, Population, Breadcrumb, Level, LevelStr) AS
(
select ID, ParentId, Name, Population
, convert(varchar(max),Name) as [Breadcrumb]
, Level = 1
, convert(varchar(max),'Level1')
from #Populations
where ParentId is null
union all
select p.ID, p.ParentId, p.Name, p.Population
,convert(varchar(max),[Breadcrumb] + ', ' + p.Name)
,Level + 1, convert(varchar(max)
,LevelStr + ', Level' + convert(varchar(2), Level + 1))
From #Populations p
inner join FirstLevel on FirstLevel.ID = p.ParentId
)
select top 1 LevelStr + ', Population' as CsvRow
from FirstLevel
where Level = (select max(level) from FirstLevel)
union all
select Breadcrumb + ',' + coalesce(replicate(',',(select max(level) from FirstLevel) - Level - 1), '') + ' ' + convert(varchar(20), Population)
from FirstLevel
drop table #Populationshttps://stackoverflow.com/questions/7699936
复制相似问题