这是我的示例表数据:
CustomerType Date Records
1 2018-01-01 233
2 2018-01-01 12
1 2018-01-02 0
2 2018-01-02 34
1 2018-01-03 0
2 2018-01-03 35
1 2018-01-04 0
2 2018-01-04 0
1 2018-01-05 5562
2 2018-01-05 3
我希望输出显示CustomerType为每个CustomerType提取的最大0记录条纹。换句话说,我希望每个特定CustomerType连续的最大零记录数
示例输出
CustomerType MaxZeroRecordsStreak
1 3
2 1
到目前为止我得到的最远的是这样的:
SELECT CustomerType,
(SELECT COUNT(*)
FROM Table1 as t1
AND Records = '0'
AND t1.Date <= t2.Date) AS MaxZeroRecordsStreak
FROM Table2 As t2
ORDER BY CustomerType ASC;
但这显然不是我想要的。
对此复杂查询的任何帮助都将不胜感激。
答案 0 :(得分:1)
大多数数据库都支持ANSI标准窗口函数。您可以使用row_numbers()
的差异来执行此操作。以下内容获取客户类型的所有零序列:
select customertype, count(*) as num_zeros
from (select t.*,
row_number() over (partition by records, customertype order by date) as seqnum_rt,
row_number() over (partition by customertype order by date) as seqnum_t
from t
) t
where records = 0
group by records, customertype, seqnum_t - seqnum_rt;
只需将此作为子查询使用即可获得最大值:
select customertype, max(num_zeros)
from (select customertype, count(*) as num_zeros
from (select t.*,
row_number() over (partition by records, customertype order by date) as seqnum_rt,
row_number() over (partition by customertype order by date) as seqnum_t
from t
) t
where records = 0
group by records, customertype, seqnum_t - seqnum_rt
) t
group by customertype;