2013-04-29 72 views
4

在SQL Server 2008中,我有這樣的結果:TSQL,我如何分組行?

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

,我要 「壓縮」 它像下面這樣:

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

讓我看看你的http://sqlfiddle.com/ – 2013-04-29 08:22:52

+0

查詢規範化表.. – 2013-04-29 08:22:56

回答

8

嘗試查詢

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

SQL Fiddle

+0

謝謝, 有用! – alesic 2013-04-29 08:39:19

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  [email protected] 
Name2 654987624 street2   [email protected] 

DEMO

+0

+1您也可以使用DISTINCT關鍵字。 http://sqlfiddle.com/#!3/abd17/10 – 2013-04-29 08:38:35