【问题标题】:Window function based on transition of a column value基于列值转换的窗口函数
【发布时间】:2022-01-26 08:55:57
【问题描述】:

我有如下响应查询

dest emp
893106 0
717205 1
888305 0
312301 1
645100 0
222001 0
761104 1

我想获得窗口函数来分隔如下行:

dest emp
893106 0
717205 1
dest emp
888305 0
312301 1
dest emp
645100 0
222001 0
761104 1

所以每个窗口必须以 emp value = 0 开始并以 emp value = 1 结束。它必须检测列值的转换。

【问题讨论】:

  • 你如何指出哪些 dest 值被分组在一起,即 partitions
  • 您的示例数据缺少排序列。 Sql 表是一组无序的行。
  • 分区必须依赖这里的emp值,在每个过渡0->1创建分区。 dest 值可以是任何值
  • 在以某种方式对行进行排序之前,您无法检测到列值的转换。

标签: sql postgresql window-functions


【解决方案1】:

响应查询将按保持结果集中给定顺序的某个字段排序,以使查询正常工作。

您将在数据中查找当前值为 0 且先前值为 1 的模式,并开始一个新的 grp,如下所示。

这是一种方法。

create table t(id int, dest int, emp int);

insert into t 
select 1,893106,0 union all
select 2,717205,1 union all
select 3,888305,0 union all
select 4,312301,1 union all
select 5,645100,0 union all
select 6,222001,0 union all
select 7,761104,1;

commit;

with main_data
as (
select *,case when emp=0 and lag(emp) over(order by id)=1 then
                   1
                   else 0
         end as grp_val
  from t
    )
select *,sum(grp_val) over(order by id) as grp
  from main_data;

+====+========+=====+=========+=====+
| id | dest   | emp | grp_val | grp |
+====+========+=====+=========+=====+
| 1  | 893106 | 0   | 0       | 0   |
+----+--------+-----+---------+-----+
| 2  | 717205 | 1   | 0       | 0   |
+----+--------+-----+---------+-----+
| 3  | 888305 | 0   | 1       | 1   |
+----+--------+-----+---------+-----+
| 4  | 312301 | 1   | 0       | 1   |
+----+--------+-----+---------+-----+
| 5  | 645100 | 0   | 1       | 2   |
+----+--------+-----+---------+-----+
| 6  | 222001 | 0   | 0       | 2   |
+----+--------+-----+---------+-----+
| 7  | 761104 | 1   | 0       | 2   |
+----+--------+-----+---------+-----+

https://sqlize.online/sql/psql14/053971a469e423ef65d97984f9017fbf/

【讨论】:

  • 谢谢!它是如此简单和优雅,它适合 100%
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多