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

获取满足给定条件的连续天数

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

获取满足给定条件的连续天数

此查询将产生每一行的计数:

SELECt allocation, d, count(*) OVER (PARTITION BY allocation, part ORDER BY d) AS cFROM (  SELECt allocation, d,         d - row_number() OVER (PARTITION BY allocation ORDER BY d) AS part  FROM t)ORDER BY d;

然后,您可以对其进行过滤以找到给定行的计数:

SELECt cFROM (  SELECt allocation, d, count(*) OVER (PARTITION BY allocation, part ORDER BY d) AS c  FROM (    SELECt allocation, d,d - row_number() OVER (PARTITION BY allocation ORDER BY d) AS part    FROM t  ))WHERe d = DATE '2015-01-05';

解释:

派生表用于

part
为每个日期和分配计算不同的“分区” :

  SELECt allocation, d,         d - row_number() OVER (PARTITION BY allocation ORDER BY d) AS part  FROM t

结果是:

allocation  dpart--------------------------------Same        01.01.15    31.12.14Good        02.01.15    01.01.15Same        03.01.15    01.01.15Same        04.01.15    01.01.15Same        05.01.15    01.01.15Good        06.01.15    04.01.15

由产生的具体日期

part
无关紧要。分配中的每个“组”日期都只是相同的某个日期。然后,您可以
(allocation, part)
使用
count(*)over(...)
window函数计算相同值的数量:

SELECt allocation, d, count(*) OVER (PARTITION BY allocation, part ORDER BY d) AS cFROM (...)ORDER BY d;

产生想要的结果。

数据

我已将下表用作示例:

CREATE TABLE t AS (  SELECt DATE '2015-01-01' AS d, 'Same' AS allocation FROM dual UNIOn ALL  SELECt DATE '2015-01-02' AS d, 'Good' AS allocation FROM dual UNIOn ALL  SELECt DATE '2015-01-03' AS d, 'Same' AS allocation FROM dual UNIOn ALL  SELECt DATE '2015-01-04' AS d, 'Same' AS allocation FROM dual UNIOn ALL    SELECt DATE '2015-01-05' AS d, 'Same' AS allocation FROM dual UNIOn ALL  SELECt DATE '2015-01-06' AS d, 'Good' AS allocation FROM dual);


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

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

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