gpt4 book ai didi

SQL Server,查找任意值序列

转载 作者:行者123 更新时间:2023-12-02 07:54:19 25 4
gpt4 key购买 nike

假设我们有一个维护表

Customer LastLogin ActionType
1 12/1/2007 2
1 12/2/2007 2
etc.

我们想要一份所有客户的列表,这些客户在给定年份的任何时候都有一个或多个连续 14 天的连续登录操作类型 2。

我当然可以很容易地用代码做到这一点,甚至在小集合上也相当快。在 SQL 中有没有非游标的方法?

最佳答案

这将选择至少连续执行两次相同类型操作的所有客户。

WITH    rows AS 
(
SELECT customer, action,
ROW_NUMBER() OVER (PARTITION BY customer ORDER BY lastlogin) AS rn
FROM mytable
)
SELECT DISTINCT customer
FROM rows rp
WHERE EXISTS
(
SELECT NULL
FROM rows rl
WHERE rl.customer = rp.customer
AND rl.rn = rp.rn + 1
AND rl.action = rp.action
)

下面是针对操作 2 的更高效的查询:

WITH    rows AS 
(
SELECT customer, ROW_NUMBER() OVER (PARTITION BY customer ORDER BY lastlogin) AS rn
FROM mytable
WHERE action = 2
)
SELECT DISTINCT customer
FROM rows rp
WHERE EXISTS
(
SELECT NULL
FROM rows rl
WHERE rl.customer = rp.customer
AND rl.rn = rp.rn + 1
)

更新 2:

要选择不间断的范围:

WITH    rows AS 
(
SELECT customer, action, lastlogin
ROW_NUMBER() OVER (PARTITION BY customer ORDER BY lastlogin) AS rn
ROW_NUMBER() OVER (PARTITION BY customer, action ORDER BY lastlogin) AS series
FROM mytable
)
SELECT DISTINCT customer
FROM (
SELECT customer
FROM rows rp
WHERE action
GROUP BY
customer, actioncode, series - rn
HAVING
DETEDIFF(day, MIN(lastlogin), MAX(lastlogin)) >= 14
) q

此查询计算两个系列:一个返回连续的 ORDER BY laSTLogin,第二个按 action 划分:

action  logindate rn  series diff = rn - series
1 Jan 01 1 1 0
1 Jan 02 2 2 0
2 Jan 03 3 1 2
2 Jan 04 4 2 2
1 Jan 05 5 3 2
1 Jan 06 6 4 2

只要两种方案的区别相同,系列不间断。每次中断都会打断系列。

这意味着 (action, diff) 的组合定义了不间断的组。

我们可以按action、diff 进行分组,在组中找到MAXMIN 并对其进行过滤。

如果您需要选择 14 行而不是连续 14 天,只需过滤 COUNT(*) 而不是 DATEDIFF.

关于SQL Server,查找任意值序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1820877/

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