栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SQL Server,查找任意值序列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SQL Server,查找任意值序列

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

WITH    rows AS         (        SELECt  customer, action,     ROW_NUMBER() OVER (PARTITION BY customer ORDER BY lastlogin) AS rn        FROM    mytable        )SELECt  DISTINCT customerFROM    rows rpWHERe   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 customerFROM    rows rpWHERe   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 customerFROM    (        SELECt  customer        FROM    rows rp        WHERe   action        GROUP BY     customer, actionpre, series - rn        HAVINg     DETEDIFF(day, MIN(lastlogin), MAX(lastlogin)) >= 14        ) q

此查询计算两个序列:一个返回连续的序列

ORDER BY lastlogin
,第二个通过
action
另外划分:

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

只要两种方案之间的差异相同,该系列就不会中断。每次打断都会打断系列。

这意味着(

action, diff
)的组合定义了不间断的组。

我们可以按分组

action, diff
,在分组中找到
MAX
MIN
,然后对其进行过滤。

如果您需要选择

14
行而不是
14
连续几天,只是过滤的
COUNT(*)
,而不是
DATEDIFF



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/391417.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号