使用Window-Functions在Postgresql中进行数据分区

时间:2016-06-06 16:28:07

标签: postgresql window-functions

我有桌子' Z':

id|zone|name
------------
1 | 34 |  a
2 | 14 |  b
3 | 99 |  c
4 | 99 |  d
5 | 90 |  e
6 | 99 |  c

查询

SELECT *,dense_rank() (OVER ORDER BY zone) FROM Z

返回:

id|zone|name|dense_rank
-----------------------
1 | 34 |  a | 2
2 | 14 |  b | 1
3 | 99 |  c | 4
4 | 99 |  d | 4               
5 | 90 |  e | 3
6 | 99 |  c | 4

首先(不太重要)的问题是: 是否有可能通过id:

排序dense_rank
id|zone|name|dense_rank
-----------------------
1 | 34 |  a | 1
2 | 14 |  b | 2
3 | 99 |  c | 3
4 | 99 |  d | 3               
5 | 90 |  e | 4
6 | 99 |  c | 3

但我的最终目标是在字段' zone'时更改数据分区。更改。我需要一张这样的桌子:

id|zone|name|window-function?
-----------------------
1 | 34 |  a | 1
2 | 14 |  b | 2
3 | 99 |  c | 3
4 | 99 |  d | 3               
5 | 90 |  e | 4
6 | 99 |  c | 5

有什么想法吗?

非常感谢

1 个答案:

答案 0 :(得分:2)

查询"最终目标"是:

SELECT *,
       SUM( x ) OVER (ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )
FROM ( 
    SELECT *,
       CASE WHEN zone = lag( zone ) over ( order by id )
                 THEN 0 ELSE 1 END As x
    FROM Z
) x 

对于不那么重要的"质疑查询是

SELECT z.*, p.dense_rank
FROM z
JOIN (
   SELECT ZONE, row_number() over (order by ID ) as dense_rank
   FROM (
    SELECT zone, min ( id ) as id
    FROM z
    GROUP BY zone
   ) o
) p ON z.zone = p.zone
ORDER BY id