TSQL,如何对行进行分组?

时间:2013-04-29 08:19:13

标签: sql sql-server tsql grouping

在SQL Server 2008中,我有这样的结果:

 contact  phone       address    email
 Name1    435551123     
 Name1                street 1  
 Name1                           name1@domain.com
 Name2    654987624
 Name2                street2   
 Name2                           name2@domanin.com

我希望像以下一样“压缩”它:

 contact  phone       address    email
 Name1    435551123   street 1   name1@domain.com       
 Name2    654987624   street2    name2@domanin.com

2 个答案:

答案 0 :(得分:8)

尝试查询

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

<强> SQL Fiddle

答案 1 :(得分:2)

您可以使用CTE和一些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

结果:

CONTACT PHONE       ADDRESS         EMAIL
Name1   435551123   street 1        name1@domain.com
Name2   654987624   street2         name2@domanin.com

DEMO