gpt4 book ai didi

sql - T-SQL 窗口函数 - 计算间隙

转载 作者:行者123 更新时间:2023-12-01 16:22:55 26 4
gpt4 key购买 nike

我想计算窗口 v 中的间隙(用 NULL 填充的列),但我不知道如何进行。

Screenshot

IF OBJECT_ID('tempdb..#X') IS NOT NULL DROP TABLE #X;

CREATE TABLE #X
(
ID INT IDENTITY(1,1) PRIMARY KEY,
v INT
);

INSERT INTO #X
SELECT 121 UNION ALL SELECT NULL UNION ALL SELECT NULL
UNION ALL SELECT 312 UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL
UNION ALL SELECT 123 UNION ALL SELECT NULL UNION ALL SELECT NULL
UNION ALL SELECT 415 UNION ALL SELECT 416 UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL
UNION ALL SELECT 200;


SELECT
ID, v, s, n, m, x, c
FROM
(SELECT
ID, v,
MAX(v) OVER (PARTITION BY c) s,
ROW_NUMBER() OVER (PARTITION BY c ORDER BY ID DESC) n,
ROW_NUMBER() OVER (PARTITION BY c ORDER BY ID) - 1 m,
COUNT(CASE WHEN v IS NULL THEN 1 END) OVER (PARTITION BY c) x,
c
FROM
(SELECT
ID, v,
-- c = COUNT(CASE WHEN v IS NULL THEN 1 END) OVER (ORDER BY ID)
c = COUNT(v) OVER (ORDER BY ID)
FROM
#X) a
) a
ORDER BY
ID;

计算 c 很接近,但它不适用于连续的两个填充列。

谁能给点提示吗?

<小时/>

谢谢你们,这对我现在有用。

Screenshot solved solution

最佳答案

如果要枚举 NULL 的周期,可以使用累积计数来获取非空值,然后枚举它们:

select t.*,
(case when v is null then dense_rank() over (partition by v order by null_grp)
end) as newcolumn
from (select t.*,
count(v) over (order by id) as null_grp
from t
) t;

Here是一个数据库<> fiddle 。

关于sql - T-SQL 窗口函数 - 计算间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60641840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com