加入两个 SQL 服务器表时排除空白列

Exclude blank column while Joining two SQL server tables

我将一组车辆零件存储在两个表中,如下所示:

来源Table1:

Vehicle_ID Part1 Part2 Part3 Part4 Part5
1 10 20 30
2 10 20
3 10

来源Table2:

Vehicle_ID Part6 Part7 Part8 Part9 Part10
1 40
2 30 50 60
3 30

需要 Table 如下所示:

Vehicle_ID Part1 Part2 Part3 Part4 Part5
1 10 20 30 40
2 10 20 30 50 60
3 10 30

Part 列的最大值,最多 5 个。

我尝试了 Union all 语句,但该语句与排除空白列无关。

请分享您解决我问题的经验。

您需要对两个表中的行进行逆透视和透视。

数据:

SELECT *
INTO Table1
FROM (VALUES
   (1, 10, 20,   30,   NULL, NULL), 
   (2, 10, 20,   NULL, NULL, NULL), 
   (3, 10, NULL, NULL, NULL, NULL),     
   (4, 40, NULL, NULL, NULL, NULL)      
) v (Vehicle_ID, Part1, Part2, Part3, Part4, Part5)

SELECT *
INTO Table2
FROM (VALUES
   (1, 40, NULL, NULL, NULL, NULL),     
   (2, 30, 50,   60,   NULL, NULL),
   (3, 30, NULL, NULL, NULL, NULL),
   (5, 50, NULL, NULL, NULL, NULL)
) v (Vehicle_ID, Part6, Part7, Part8, Part9, Part10)

声明:

SELECT 
   Vehicle_ID,
   MAX(CASE WHEN RN = 1 THEN Part END) AS Part1,
   MAX(CASE WHEN RN = 2 THEN Part END) AS Part2,
   MAX(CASE WHEN RN = 3 THEN Part END) AS Part3,
   MAX(CASE WHEN RN = 4 THEN Part END) AS Part4,
   MAX(CASE WHEN RN = 5 THEN Part END) AS Part5
FROM (
   SELECT 
      COALESCE(t1.Vehicle_ID, t2.Vehicle_ID) AS Vehicle_ID,
      a.*,
      ROW_NUMBER() OVER (PARTITION BY COALESCE(t1.Vehicle_ID, t2.Vehicle_ID) ORDER BY a.Part_ID) AS RN
   FROM Table1 t1
   FULL OUTER JOIN Table2 t2 ON t1.Vehicle_ID = t2.Vehicle_ID
   CROSS APPLY (VALUES
      (1, t1.Part1),
      (2, t1.Part2),
      (3, t1.Part3),
      (4, t1.Part4),
      (5, t1.Part5),
      (6, t2.Part6),
      (7, t2.Part7),
      (8, t2.Part8),
      (9, t2.Part9),
      (10, t2.Part10)
   ) a (Part_ID, Part)
   WHERE a.Part IS NOT NULL
) t
GROUP BY Vehicle_ID

结果:

Vehicle_ID Part1 Part2 Part3 Part4 Part5
1 10 20 30 40
2 10 20 30 50 60
3 10 30
4 40
5 50