我有一个“国家”表,其中包含国家/地区的人口数据。有 5 个不同的“region_id” - 10,20,30,40,50 我有这样的疑问:
select name, region_id,
sum(population) over (partition by region_id) as tot_pop
from countries
当我运行查询时,行按“region_id”的升序返回 - 按 10、20、30、40、50 的顺序。这是因为我说“按region_id 分区”吗?那么,partition by column_name 是否对column_name 进行排序,或者我是否以这种方式得到结果,因为行本身是按region_id 的升序插入表中的? 假设我有这张表: |流行 |Region_id | |:--------:|:--------------:| | 1000 | 1000 10 | 10 | 2000 |20 | | 9000 |10 | | 3000 |10 | | 2000 |20 | | 4000 |20 |
因此,当执行按region_id分区时,我假设记录按以下顺序获取:
|流行 |Region_id | |:--------:|:--------------:| | 1000 | 1000 10 | 10 | 9000 | 10 | 10 | 3000 | 10 | 10 | 2000 | 20 | 20 | 2000 | 20 | 20 | 4000 | 20 | 20 我的假设正确吗?
此查询计算每个region_id的总人口并返回结果。 PARTITION BY Region_id 按 Region_id 对行进行分组,以便进行 SUM(population) 计算,但它不会对行进行排序。
要显式控制结果的顺序,您应该在查询中使用 ORDER BY 子句。
SELECT name, region_id,
SUM(population) OVER (PARTITION BY region_id) AS tot_pop
FROM countries
ORDER BY region_id;
当您添加 ORDER BY Region_id 时,它会显式地按 Region_id 对结果集进行排序。