连续行的条件计数

时间:2015-11-14 00:50:48

标签: ms-access access-vba

对于给定的当前客户,我试图找到他们已连续多年与我们续订政策。我对如何做到这一点的想法是将当前行中的字段与前一行匹配。我正在尝试为此编写一个函数,但如果有更简单的方法请告诉我。以下是我对该功能的了解

Option Compare Database
'Renewal Count Returns count of consecutive renewals
Public Function RenewCount(strLocationID As Integer, _
                   strQuoteID As Integer, _
                   strOriginalQuoteID As Variant) As String
Static strLastLocationID As Integer
Static strLastQuoteID As Integer
Static strCount As Integer
If strLocationID = strLastLocationID And strOriginalQuoteID = strLastQuoteID Then
    strCount = strCount + 1
Else
    strLastLocationID = strLocationID
    strLastQuoteID = strQuoteID
    strCount = 0

End If
RenewCount = strCount
End Function

以下是数据的一些示例

LocationID  QuoteID OriginalQuoteID
2            1094117    
2            1125718    1094117
2            1148296    1125718
2            1176466    1148296
5            1031892   
5            1044976    1031892
5            1059216    1044976
5            1077463    1059216

我也可以操纵每个政策的日期。 我的想法是拥有以下内容,并找到每个位置的最后一列的最大值。

LocationID  QuoteID OriginalQuoteID Renewal_Count
2            1125718    1094117       0
2            1148296    1125718       1
2            1176466    1148296       2
5            1031892                  0
5            1044976    1031892       1
5            1059216    1044976       2
5            1077463    1059216       3
5            1098124    1077463       4
5            1100215                  0
5            1198714    1100215       1
5            1254125    1198714       2

任何帮助将不胜感激。感谢

我忘了提到这已按位置ID排序,并且对于任何新策略,OriginalQuoteID都将为null。当我尝试运行该功能时,我得到#num!在大多数行的列中。我想要的是给定的QuoteID连续续订的数量。因此对于locationID 5 QuoteID 1254125的上述内容已经有2次续订。

1 个答案:

答案 0 :(得分:0)

这可能有用(似乎与我的测试一起) - 在自身上创建一个笛卡尔积,将QuoteID链接到OriginaQuoteID并计算。

SELECT  T1.LocationID,
        T1.QuoteID,
        T1.OriginalQuoteID
FROM    Table1 T1, Table1 T2
WHERE   T1.QuoteID = T2.OriginalQuoteID

获取每个LocationID的计数(加1来计算Null字段):

SELECT      COUNT(*)+1
FROM        Table1 T1, Table1 T2
WHERE       T1.QuoteID = T2.OriginalQuoteID
GROUP BY    T1.LocationID

或者如果您更喜欢加入:

SELECT      COUNT(*)+1
FROM        Table1 T1 INNER JOIN Table1 T2 ON T1.QuoteID = T2.OriginalQuoteID
GROUP BY    T1.LocationID