0

我有一个可以正常工作的存储过程,但不明白它为什么工作的理论。我通过使用日期部分和密集等级来识别连续的时间段(通过其他地方的帮助找到解决方案)。

        select 
            c.bom
            ,h.x
            ,h.z
            ,datepart(year, c.bom) * 12 + datepart(month, c.bom) -- this is returning a integer value for the year and month, allowing us to increment the number by one for each month
            - dense_rank() over ( partition by h.x order by datepart(year, c.bom) * 12 + datepart(month, c.bom)) as grp -- this row does a dense rank and subtracts out the integer date and rank so that consecutive months (ie consecutive integers) are grouped as the same integer

        from 
            #c c

            inner join test.vw_info_h h
            on h.effective_date <= c.bom
            and (h.expiration_date is null or h.expiration_date > c.bom)

我从理论上理解分组功能发生了什么。

乘以年 * 12 + 月如何工作?为什么我们将年份相乘?后端发生了什么?

4

1 回答 1

1

日期的年份部分是一个整数值。由于一年有 12 个月,因此将年份值乘以 12 可得出到达该年第一个月所经过的总月数。

这是一个例子。取 2012 年 2 月 11 日的日期(CCYYMMDD 格式的 20120211)

2012 * 12 = 24144 个月,从时间本身开始。

24144 + 2 个月(二月)= 24146。

将年份值乘以一年中的月数可以让您建立与月份相关的偏移量,而无需进行任何编码来处理一年结束和另一年开始之间的边缘情况。例如:

11/2011 -> 24143 12/2011 -> 24144 01/2012 -> 24145 02/2012 -> 24146

于 2012-10-19T17:41:28.743 回答