我有如下回應查詢
| 目的地 | 臨時工 |
|---|---|
| 893106 | 0 |
| 717205 | 1 |
| 888305 | 0 |
| 312301 | 1 |
| 645100 | 0 |
| 222001 | 0 |
| 761104 | 1 |
我想獲得視窗函式來分隔如下行:
| 目的地 | 臨時工 |
|---|---|
| 893106 | 0 |
| 717205 | 1 |
| 目的地 | 臨時工 |
|---|---|
| 888305 | 0 |
| 312301 | 1 |
| 目的地 | 臨時工 |
|---|---|
| 645100 | 0 |
| 222001 | 0 |
| 761104 | 1 |
所以每個視窗都必須以emp value = 0開始,以emp value = 1結束。它必須檢測列值的轉換。
uj5u.com熱心網友回復:
回應查詢將由某個欄位排序,該欄位維護結果集中給定的順序,以便查詢作業。
您將在資料中查找當前值為 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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395782.html
標籤:sql PostgreSQL的 窗函数
上一篇:Postgresql合并列
