考虑以下人口结构。
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 查询来返回每个级别的人口。即,将总结各州的人口以找到国家的人口。 同样将总结国家人口以找到大陆人口。
最佳答案
如果你想在大陆之后求和,一种方法是添加一个大陆列
大陆之后的总和
SELECT sum(Population) FROM yourTable GROUP BY continent.
另一种方法是这样的硬编码列表
大陆后的总和
只需将 sum
和 group by
与 REGEXP_SUBSTR
和硬编码列表一起使用。在我的案例中,德国、英国应该代表欧洲。
SELECT sum(Population) FROM yourTable GROUP BY REGEXP_SUBSTR('Name','(.*)_?') IN ('England', 'Germany')
关于sql - 对大陆、国家和州的表中的层次值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35884683/