79123423

Date: 2024-10-24 19:48:29
Score: 1
Natty:
Report link

For those that don't want a comma before the "and" when there are two records, here is a slight variation of the answer by @johncappelletti.

Select Distinct
      OwnerID
     ,stuff( ( Select case when row_number() over(order by pn) = 2 and nullif(sum(1) over() ,1) = 2
                               then ' and ' 
                           when row_number() over(order by pn) = nullif(sum(1) over() ,1)
                               then ', and ' 
                           else ', ' 
                       end + pn  
                FROM (Select distinct pn 
                       From @YourTable
                        Where OwnerID = A.OwnerId
                     ) e 
                Order By PN
                For XML Path('')), 1, 2, '')  AS [Pet(s)]
 From @YourTable A
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @johncappelletti
  • Low reputation (1):
Posted by: user3546122