SQL Server:合并具有相同ID但列值不同的两行

时间:2020-01-18 08:30:05

标签: sql sql-server pivot

当Microsoft SQL Server中具有相同ID但不同列值的不同行时,我试图将它们合并为一个。

例如,我有

ID     SubID          Desc
-----------------------------------
1      170            PC-money
1      171            PC-windows
2      170            PC-free
2      171            PC-open

我想得到这个输出:

ID     SubID          Desc                 Desc1
---------------------------------------------------    
1      170            PC-money             PC-free   
1      171            PC-windows           PC-open

2 个答案:

答案 0 :(得分:1)

尝试:

SELECT 
    t1.id,t1.subtype,t1.DESC ,t2.DESC  
FROM 
    table1 AS t1
    LEFT JOIN 
    table1 AS t2 
    ON t1.id != t2.id AND t1.subtype = t2.subtype
WHERE 
    t1.id = 1

答案 1 :(得分:0)

Conditional Aggregation通过按SubID列分组:

SELECT MIN([ID]) AS [ID], [SubID], 
       MAX(CASE WHEN [ID]=1 THEN [Desc] END) AS [Desc],
       MAX(CASE WHEN [ID]=2 THEN [Desc] END) AS [Desc1]
  FROM t
 GROUP BY [SubID] 

pivot,或者:

SELECT t2.[ID], t1.[SubID], t1.[1] AS [Desc], t1.[2] AS [Desc1]
  FROM t
 PIVOT
 (
  MAX([Desc]) FOR [ID] IN ([1],[2])
 ) t1
 CROSS JOIN (SELECT MIN([ID]) AS [ID] FROM t) t2

或考虑使用LEFT JOIN来选择ID值最小的记录:

SELECT t2.[ID], t1.[SubID], t2.[Desc], t1.[Desc] AS [Desc1]
  FROM t AS t1
  LEFT JOIN t AS t2 
         ON t1.[ID] != t2.[ID] 
        AND t1.[SubID] = t2.[SubID]
 WHERE t2.[ID] IN ( SELECT MIN([ID]) FROM t )

Demo

P.S。 Desc不应在括号中不加保留字词。