【问题标题】:Consecutive months and gaps in SQL to get max consecutive months and max gaps monthSQL 中的连续月份和间隔以获得最大连续月份和最大间隔月份
【发布时间】:2021-10-27 19:51:29
【问题描述】:

我在尝试创建的数据集上遇到了障碍。我正在寻找连续几个月为客户开具发票。 如果几个月有中断,计数应重新开始。我的最终数据集将为我提供最大连续月数、最大或总间隔数。

这是示例表:

select 'Demo Client' as ClientName,'1' as InvoiceMonthNumber,'20201' InvoiceYearMonth,'2020' InvoiceYear
into #tempa
union select 'Demo Client','2','20202','2020'
union select 'Demo Client','3','20203','2020'
union select 'Demo Client','4','20204','2020'
union select 'Demo Client','5','20205','2020'
union select 'Demo Client','6','20206','2020'
union select 'Demo Client','7','20207','2020'
union select 'Demo Client','10','202010','2020'
union select 'Demo Client','5','20215','2021'
union select 'Demo Client','6','20216','2021'
union select 'Demo Client','7','20217','2021'
union select 'Demo Client','8','20218','2021'
union select 'Demo Client','9','20219','2021'
union select 'Demo Client','10','202110','2021'


select * 
from #tempa
where invoiceyear = 2020

select * 
from #tempa
where invoiceyear = 2021

这里,对于这个客户,最大数量。 2020 年的连续发票月份数为 7。 几个月的差距是: 2020 年第 8,9 个月 2020 年 11 月 12 日 2021 年第 1、2、3、4、5 个月 所以最大间隔是 5 个月

我正在寻找想法和逻辑。

【问题讨论】:

  • 你能添加一个想要澄清的结果吗?

标签: sql-server tsql


【解决方案1】:

您可以按当前月和下个月之间的差异进行分组。

类似这样的:

SELECT ClientName
    ,InvoiceYear
    ,COUNT(1) + 1 AS NumberOfConsecutiveMonths
FROM (
    SELECT *
        ,lead(InvoiceYearMonth) OVER (
           PARTITION BY invoiceYear ORDER BY CAST(InvoiceYearMonth AS INT)
          ) - CAST(InvoiceYearMonth AS INT) AS diff
    FROM #tempa
) a
WHERE difF = 1
GROUP BY ClientName
      ,InvoiceYear

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2020-03-01
    • 2020-12-29
    • 2022-09-23
    相关资源
    最近更新 更多