无法重置分区组(特定于Windows函数和PostgreSQL)

问题描述 投票:1回答:1

我有一个像这样的简单数据集:

SELECT UNNEST(ARRAY['A', 'A', 'A', 'B', 'B', 'A', 'C', 'B']) AS customer_name, generate_series(8, 1, -1) AS order_time;

+-------------+------------+
| customer_id | order_time |
+-------------+------------+
| "A"         | 8          |
+-------------+------------+
| "A"         | 7          |
+-------------+------------+
| "A"         | 6          |
+-------------+------------+
| "B"         | 5          |
+-------------+------------+
| "B"         | 4          |
+-------------+------------+
| "A"         | 3          |
+-------------+------------+
| "C"         | 2          |
+-------------+------------+
| "B"         | 1          |
+-------------+------------+

我正在寻找一行:

+-------------+------------+
| customer_id | order_time |
+-------------+------------+
| "A"         | 6          |
+-------------+------------+

这是说,我想获得最新的(连续的)order_time的第一个customer_id。使用以下SQL,我只能从order_time A获得“ 3”作为customer_id。我似乎无法“重置”分区。

SELECT customer_name, LAST_VALUE(order_time) OVER W
FROM
(
  SELECT UNNEST(ARRAY['A', 'A', 'A', 'B', 'B', 'A', 'C', 'B']) AS customer_name, generate_series(8, 1, -1) AS order_time
) X
WINDOW W AS (PARTITION BY customer_name ORDER BY order_time DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY order_time DESC
LIMIT 1;

使用PostgreSQL 11.5

sql postgresql window-functions gaps-and-islands
1个回答
1
投票

您可以使用之间的区别

ROW_NUMBER() OVER (ORDER BY order_time DESC)

[ROW_NUMBER() OVER (PARTITION BY customer_name ORDER BY order_time DESC)gaps-and-islands结构提供分组:

SELECT XX.customer_name, LAST_VALUE(order_time) OVER W FROM
(
 SELECT X.*, ROW_NUMBER() OVER (ORDER BY order_time DESC)-
             ROW_NUMBER() OVER (PARTITION BY customer_name ORDER BY order_time DESC) 
             AS rn

   FROM
   (
     SELECT UNNEST(ARRAY['A', 'A', 'A', 'B', 'B', 'A', 'C', 'B']) AS customer_name, 
            generate_series(8, 1, -1) AS order_time
    ) X
 ) XX
WINDOW W AS (PARTITION BY rn, customer_name ORDER BY order_time DESC 
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
LIMIT 1; 

Demo

© www.soinside.com 2019 - 2024. All rights reserved.