Grouping Sequential Numbers with like attributes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • NeoPa
    Recognized Expert Moderator MVP
    • Oct 2006
    • 32636

    #16
    Would something like the following work ?
    Code:
    WITH ctePhone AS
    (
    SELECT ROW_NUMBER() OVER(Company
                           , PhoneType
                           , LD
                             ORDER BY Phone) AS SeqNo
         , Phone
         , Company
         , PhoneType
         , LD
    FROM   @Phones
    )
    SELECT   MIN(Phone) AS First_Consecutive
           , CASE
             WHEN MIN(Phone) < MAX(Phone) THEN MAX(Phone)
             ELSE NULL
             END AS Last_Consecutive
           , MAX(SeqNo) - MIN(SeqNo) + 1 AS [Length]
           , Company
           , PhoneType
           , LD
    FROM     ctePhone
    GROUP BY Company
           , PhoneType
           , LD
    ORDER BY MIN(Phone)
    Obviously, I borrowed heavily from your work CK.

    Comment

    • Jerry Winston
      Recognized Expert New Member
      • Jun 2008
      • 145

      #17
      That's pretty CK.

      Comment

      • Joel Miller
        New Member
        • Aug 2010
        • 8

        #18
        I was able to implement Jerry's solution into my code and it worked great! Thanks so much! I never would have gotten that done by myself and I learned a lot!

        I have not been able to work on testing CK's or NEO's contributions but I am going to try that next.

        Thanks everyone! This is one of the most helpful forums I have come across.

        Comment

        • NeoPa
          Recognized Expert Moderator MVP
          • Oct 2006
          • 32636

          #19
          I've had some further thoughts on my suggestion and it appears there are situations where it would fall down. Specifically if the company etc details are the same for a bunch of records they will be treated as contiguous regardless of any breaks in the sequence.

          Comment

          Working...