【发布时间】:2016-03-09 06:40:11
【问题描述】:
考虑人口结构。
Asia(100+50+150=300)
> China (20+80=100)
> China_StateA (20)
> China_StateB (80)
> KSA (10+40=50)
> KSA_StateA (10)
> KSA_StateB (40)
> India (70+80=150)
> India_StateA (70)
> India_StateB (80)
Europe(50+15=65)
> England (50)
> England_StateA (20)
> England_StateB (30)
> Ireland (5+10=15)
> Ireland_StateA (5)
> Ireland_StateB (10)
如果我在单个数据库表中具有相同的结构,如下所示
Id Type Name ParentId Population
1 Continent Asia 0
2 Country China 1
3 State China_StateA 2 20
4 State China_StateB 2 80
5 Country KSA 1
6 State KSA_StateA 5 10
7 State KSA_StateB 5 40
8 Country India 1
9 State India_StateA 8 70
10 State India_StateB 8 80
11 Continent Europe 0
12 Country England 11
13 State England_StateA 12 20
14 State England_StateB 12 30
15 Country Ireland 11
16 State Ireland_StateA 15 5
17 State Ireland_StateB 15 10
那么我该如何编写一个 sql 查询来返回每个级别的人口。即将总结州的人口以找到国家的人口。 同样将总结国家人口以找到大陆人口。
【问题讨论】:
-
我猜您将“州”条目与“国家”条目的名称相关联。但是,您如何将大陆与国家联系起来?通过订购 ID 字段?我认为实现您想要的最简单的方法是通过函数或存储过程并遍历游标:msdn.microsoft.com/es-es/library/ms180169(v=sql.120).aspx
-
有什么办法可以查出哪个国家属于哪个大陆,哪个州属于哪个国家?我的意思是我们中的一些人知道印度在亚洲,但数据库不知道。
-
更新评论:使用hierarchical queries
标签: sql sql-server database oracle