sql - 对大陆、国家和州的表中的层次值求和

标签 sql sql-server database oracle

考虑以下人口结构。

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. 

另一种方法是这样的硬编码列表

大陆后的总和

只需将 sumgroup byREGEXP_SUBSTR 和硬编码列表一起使用。在我的案例中,德国、英国应该代表欧洲。

SELECT sum(Population) FROM yourTable GROUP BY REGEXP_SUBSTR('Name','(.*)_?') IN ('England', 'Germany')

关于sql - 对大陆、国家和州的表中的层次值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35884683/

相关文章:

sql - 不能使用与子句同名的列

MySQL删除多个表中的多行

javascript - SQL 查询上的 PHP AJAX 日期时间范围问题

mysql - CFUPDATE - 更新数据库

mysql - 我应该在SqlAlchemy中使用relationship()吗?

sql - Postgres/netezza 从多个表进行多重连接

sql - 如何使用使用计数的 sql 子查询

sql-server - SSIS 与 Oracle Data Integrator

sql - 使用不确定数量的参数时如何避免动态 SQL?

mysql - 如何在一列中选择两个条件