Increment number when the same value

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kuba S
    New Member
    • Mar 2011
    • 2

    Increment number when the same value

    Hi,

    I'm trying to do below numbering in access:

    apple 1
    apple 2
    apple 3
    apple 4
    orange 1
    orange 2
    plum 1
    peach 1
    peach 2
    peach 3

    Does anybody know how i can do that in query?
  • TheSmileyCoder
    Recognized Expert Moderator Top Contributor
    • Dec 2009
    • 2322

    #2
    This code placed in a module can act as a simple cumulative counter:
    Code:
    Public Function cumCount(strText As String) As Long
        'Cumulative counter for query
        Static strOldText As String
        Static lngCounter As Long
        If strText = strOldText Then
            lngCounter = lngCounter + 1
        Else
            lngCounter = 1
            strOldText = strText
        End If
            cumCount = lngCounter
            
    End Function
    Your SQL would then look like so, for example:
    Code:
    SELECT tbl_Fruit.Text, CumCount([Text]) AS [Counter]
    FROM tbl_Fruit
    ORDER BY tbl_Fruit.Text;

    Comment

    • Kuba S
      New Member
      • Mar 2011
      • 2

      #3
      That's exactly what i was looking for!!
      Thanks very, very much!

      Comment

      • TheSmileyCoder
        Recognized Expert Moderator Top Contributor
        • Dec 2009
        • 2322

        #4
        Your welcome
        TheSmileyCoder

        Comment

        Working...