t-SQL使用键字段将多行合并为一行

时间:2014-07-11 08:06:48

标签: sql sql-server merge rows

我有2个临时表

#data:
Key     UserID      Driver     Defect1     Defect2     Defect3    Defect4
-------------------------------------------------------------------------
124      151        Paul       Wheels      Windows      Null       Null
124      151        Paul       Null        Null         Null       Null

#data2:
Key     Defect5     Defect6    Defect7
--------------------------------------
124     Seats       Doors     Hood

我正在寻找一种方法,根据Key字段将这3行组合成一行,所以只需将它们向上滚动,忽略空值并将所有内容移动到一行。我已经将原始数据转移到了这一点,我正在寻找下一步来完成它。

我希望能够:

#data2:
Key  UserID  Driver Defect1 Defect2 Defect3  Defect4 Defect5  Defect6  Defect7
------------------------------------------------------------------------------
124  151     Paul   Wheels  Windows Null     Null    Seats    Doors    Hood

有人可以建议吗?

我的缺陷是增量的,基于行数(在枢轴之前)使用:

SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + PIVOT_CODE + ']' 
,@select_list = COALESCE(@select_list + ', ', '') + 
        'LEFT([' + PIVOT_CODE + '], CHARINDEX(''|'', ' + PIVOT_CODE + ')-1) AS [Defect_Item_' + SUBSTRING(PIVOT_CODE, 2, 4) + '] 
        '
FROM (
   SELECT DISTINCT PIVOT_CODE
   FROM (
      SELECT 'r' + CAST(ROW_NUMBER() OVER (PARTITION BY formresultkey ORDER BY Defect_Item, Defect_description) AS VARCHAR(4)) AS PIVOT_CODE
      FROM #Data3
   ) AS rows
) AS PIVOT_CODES

1 个答案:

答案 0 :(得分:0)

SELECT
  a.Key,
  a.UserID,
  MAX(a.Driver),
  MAX(a.Defect1),
  MAX(a.Defect2),
  MAX(a.Defect3),
  MAX(a.Defect4),
  MAX(b.Defect5),
  MAX(b.Defect6),
  MAX(b.Defect7)
FROM
  #data a 
LEFT OUTER JOIN
  #data2 b ON a.Key = b.Key
GROUP BY
  a.Key, a.UserID