Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL, How can I group rows?

In SQL Server 2008, I have this result:

 contact  phone       address    email
 Name1    435551123     
 Name1                street 1  
 Name1                           [email protected]
 Name2    654987624
 Name2                street2   
 Name2                           [email protected]

and I want to "compress" it like the following:

 contact  phone       address    email
 Name1    435551123   street 1   [email protected]       
 Name2    654987624   street2    [email protected]
like image 448
alesic Avatar asked Dec 27 '22 04:12

alesic


2 Answers

Try the Query

select
contact,
max(phone),
max(address),
max(email)
from table_name
group by contact

SQL Fiddle

like image 69
Prahalad Gaggar Avatar answered Jan 07 '23 04:01

Prahalad Gaggar


You could use a CTE and some OVER clauses:

WITH CTE AS (
  SELECT [contact], 
         [phone]=MAX(PHONE)OVER(PARTITION BY CONTACT), 
         [address]=MAX(address)OVER(PARTITION BY CONTACT),  
         [email]=MAX(email)OVER(PARTITION BY CONTACT),  
          RN = Row_number() 
                OVER( 
                partition BY [contact] 
                ORDER BY [contact])
  FROM dbo.Address) 
SELECT [contact], [phone], [address], [email] 
FROM CTE 
WHERE RN = 1

Result:

CONTACT PHONE       ADDRESS         EMAIL
Name1   435551123   street 1        [email protected]
Name2   654987624   street2         [email protected]

DEMO

like image 38
Tim Schmelter Avatar answered Jan 07 '23 04:01

Tim Schmelter